我有一个CSV文件,我正在尝试解析它,但在整数数据类型列上出现以下错误。在文件中,我为此列传递了空值或空白值。
[AutoMap(typeof(Test))]
[FileEntity("Test")]
public class TestFileEntity : BaseFileEntity
{
[CsvFileColumn(1)]
public int TestId { get; set; }
}
public IEnumerable<BaseFileEntity> Parse(Stream masterData, Type entityType, out IEnumerable<MasterDataFileParserError> errors)
{
var list = new List<BaseFileEntity>();
var errorList = new List<MasterDataFileParserError>();
try
{
using (var reader = new StreamReader(masterData))
{
var parser = new CsvReader(reader, new CsvHelper.Configuration.Configuration
{
HasHeaderRecord = true,
HeaderValidated = null,
MissingFieldFound = null
});
list.AddRange(parser.GetRecords(entityType).Cast<BaseFileEntity>());
}
}
catch (Exception ex)
{
if (ex.Data == null || ex.Data.Count == 0)
{
errorList.Add(new MasterDataFileParserError
{
Error = ex.Message,
Description = ex.ToString()
});
}
else
{
foreach (var key in ex.Data.Keys)
{
errorList.Add(new MasterDataFileParserError
{
Error = ex.Message,
Description = $"{key}: {ex.Data[key]}"
});
}
}
}
errors = errorList;
return list;
}
在这一行出现了异常:list.AddRange(parser.GetRecords(entityType).Cast<BaseFileEntity>());
错误信息:
解析“xyz.csv”文件中的“Test”实体时发生错误: '[{"Error":"The conversion cannot be performed.\r\n Text: ''\r\n
MemberType: System.Int32\r\n TypeConverter: 'CsvHelper.TypeConversion.Int32Converter'","Description":"CsvHelper.TypeConversion.TypeConverterException: The conversion cannot be performed.\r\n Text: ''\r\n MemberType: System.Int32\r\n TypeConverter: 'CsvHelper.TypeConversion.Int32Converter'\r\n at CsvHelper.Configuration.Configuration.<>c.<.ctor>b__148_4(CsvHelperException exception)\r\n at CsvHelper.CsvReader.d__65.MoveNext()\r\n at System.Linq.Enumerable.d__341.MoveNext()\r\n at System.Collections.Generic.List
1.AddEnumerable(IEnumerable1 enumerable)\r\n at System.Collections.Generic.List
1.InsertRange(Int32 index, IEnumerable1 collection)\r\n at Nec.Stanchion.Business.MasterDataFiles.Handling.MasterDataFileParser.Parse(Stream masterData, Type entityType, IEnumerable
1& errors) in xyz.cs 文件"}]'。
原因很明显,空字符串不能与int
数据类型兼容,所以必须有一种方法来允许int
数据类型列值为空或null。
CsvHelper版本=6.0.0.0
int?
)。 - bornfromanegg