在使用CsvHelper导入csv数据时考虑"数据"验证时,我希望使用.Valide方法将所有"数据"校验代码放入ClassMap中。
我一直在寻找如何使用.Valide方法的好例子,以确保数据符合我的业务规则,并且在违反验证规则时也会向用户发送良好的错误消息。
一个非常基本的示例位于CsvHelper网站"示例"部分的"配置/类映射/验证代码"中,位于此处:https://joshclose.github.io/CsvHelper/examples/configuration/class-maps/validation/
我能够预测地制造和捕捉使用.Valide方法设置的错误。然而,我还没有确定一种方法来向我的用户提供足够的信息,以在遇到问题时解决问题。在我看来,FieldValidationException没有包含足够有用的信息。我看到其他人问这个问题,但我看到的其他帖子对这个问题没有足够的答案。请参阅下面的代码和评论。
class Program
{
static void Main(string[] args)
{
try
{
// load comma separated data into string for processing
var s = new StringBuilder();
s.AppendLine("Id,Name");
s.AppendLine("1,one-e");
// Begin processing
using (var reader = new StringReader(s.ToString()))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
csv.Context.RegisterClassMap<FooMap>();
var contents = csv.GetRecords<Foo>().ToList();
Console.WriteLine($"Read file: length is : {contents.First().Id},{contents.First().Name},{contents.First().Date}");
}
}
catch (FieldValidationException fieldExc)
{
// this exception object does not appear to hold any information about the column that is in error. It does not seem to specify what the error entails.
// It appears to contain the value that created the exception? In a 'string' field called: "Field".
// I would really like further information about what is specifically is wrong with which column and possibly which row.
Console.WriteLine($"Error Message is : {fieldExc.Message}");
}
catch(TypeConverterException converterExc)
{
// If I happen to have a conversion exception, then the resulting TypeConversionException has good information to advise
// a user to correct an error.
var message = FriendlyErrorText(converterExc);
Console.WriteLine(message);
}
catch (Exception exc)
{
Console.WriteLine($"Error Message is : {exc.Message}");
}
finally
{
Console.WriteLine("test executed");
Console.ReadKey();
}
}
public class Foo
{
public int Id { get; set; }
public string Name { get; set; }
public DateTimeOffset? Date { get; set; }
}
public class FooMap : ClassMap<Foo>
{
public FooMap()
{
Map(m => m.Id);
Map(m => m.Name).Validate(field => !field.Field.Contains("-"));
}
}
public static string FriendlyErrorText(TypeConverterException exception)
{
var column = exception?.MemberMapData?.Member?.Name ?? "Unknown";
string typeConversion;
switch (exception?.TypeConverter?.ToString())
{
case "Int32Converter":
typeConversion = "integer";
break;
default:
typeConversion = exception?.TypeConverter?.GetType()?.Name ?? "Unknown";
break;
}
var message = $"There was an error importing the text data '{exception?.Text ?? "Unknown"}' into the column {column}. The target column is of type {typeConversion}";
return message;
}
}
FieldValidationException
包括CsvContext
,它拥有您所需要的大部分内容。
catch (FieldValidationException fieldExc)
{
var message = string.Empty;
var headerIndex = fieldExc.Context.Reader.CurrentIndex;
if(fieldExc.Context.Reader.HeaderRecord[headerIndex].ToLower() == "name")
{
message = "Name cannot contain a dash.";
}
Console.WriteLine($"Error Message is : Field Validation Exception on Row: {fieldExc.Context.Parser.Row}, Message: {message} Original Text: "{fieldExc.Field}"");
}