我正在使用乔希·克洛斯构建的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 "";
}
}
然后,此方法更新数据库
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
{
...
}
}
我去掉了一些日志和数据库逻辑,以缩短代码片段。我读过Fluent Mapping,但我对如何实现它感到困惑?我知道我必须构建一个类,但是如何引用/配置mapper类的使用?
这里有一个来自Josh网站的例子;
http://joshclose.github.io/CsvHelper/#reading-reading-all-records