使用CsvHelper库,如果Map定义了Convert,则不会触发验证。
的例子:
Map(m => m.ProjectStock)
.Validate(x =>
csvMapHelper.TrueStringsList.Contains(x.Field) || csvMapHelper.FalseStringList.Contains(x.Field))
.Convert(args =>
{
var projectStock = args.Row.GetField("ProjectStock");
return csvMapHelper.TrueStringsList.Contains(projectStock);
});
如果我运行这段代码,只触发Convert,而跳过Validate。
我做错了什么?
我不知道为什么Validate
方法不着火。然而,我相信有一种更简单的方法来做你想做的事。
void Main()
{
using (var reader = new StringReader("Id,Name,ProjectStockn1,Jordan,takn2,Beth,no"))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
csv.Context.TypeConverterOptionsCache.GetOptions<bool>().BooleanTrueValues.AddRange(CsvMapHelper.TrueStringsList);
csv.Context.TypeConverterOptionsCache.GetOptions<bool>().BooleanFalseValues.AddRange(CsvMapHelper.FalseStringList);
var records = csv.GetRecords<Foo>().ToList();
}
}
public class Foo
{
public int Id { get; set; }
public string Name { get; set; }
public bool ProjectStock { get; set; }
}
public class CsvMapHelper
{
public static List<string> TrueStringsList => new List<string> { "yes", "true", "tak" };
public static List<string> FalseStringList => new List<string> { "no", "false", "nie" };
}