我正在使用由乔希·克洛斯构建的CsvHelper库。我认为获取.csv文件的数据源有一种方法可以用正确的命名约定来掩蔽或“别名”列标题。不幸的是,情况并非如此,所以我想使用Fluent类映射,但我不清楚如何实现它。
我创建了下面的类(简化为这篇文章)
public class PaymentType
{
public int PaymentTypeId { get; set; }
public string BusinessUnit { get; set; }
public string Region { get; set; }
public string Status { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public decimal Amount { get; set; }
public string Name { get; set; }
}下面的方法在另一个类中下载并保存该文件
private string DownloadDS(string getURL, string fileName)
{
try
{
//CSV path
string url = getURL;
//Where to save and retrieve CSV file
string path = AppDomain.CurrentDomain.BaseDirectory + "ImportedFiles\\" + fileName;
//Download file and save it
WebClient client = new WebClient();
client.DownloadFile(url, path);
return path;
}
catch
{
return "";
}
}然后,此方法更新db。
private void UpdateDB(string path, string fileName)
{
try
{
//read in file with CsvReader object and output to an enumerable object
var csv = new CsvReader(new StreamReader(path));
var importedPaymentTypes = csv.GetRecords<ImportPaymentTypes>();
//Save each payment type record to the db. If record exhsists, update it, if not, add it.
...
}
catch
{
...
}
}为了缩短代码片段,我去掉了一些日志记录和db逻辑。我读过关于Fluent映射的文章,但我对如何实现它感到困惑?我知道我必须构建一个类,但是如何引用/配置mapper类的使用呢?
以下是乔希网站的一个例子;
http://joshclose.github.io/CsvHelper/#reading-reading-all-records
发布于 2015-09-16 14:47:42
请看一下映射部分。http://joshclose.github.io/CsvHelper/#mapping
通过以下操作注册映射:
csv.Configuration.RegisterClassMap<PaymentTypeMap>();https://stackoverflow.com/questions/32597840
复制相似问题