CsvHelper: "Incorrect number of arguments for constructor" 当使用属性映射属性时

CsvHelper: "Incorrect number of arguments for constructor" when using attributes to map properties

我正在使用 CsvHelper 从 CSV 中读取数据,尽管在每个字段上方都使用了属性,但它抛出错误“构造函数的参数数量不正确”。示例如下:

public class MyClass {
    [Name("Id")]
    public int AwardId { get; set; }
    
    //[Ignore]
    public List<string> IgnoreList { get; set; }

    [Name("DateField")]
    public Tuple<DateTime, DateTime> TwoDates { get; set; }

    public MyClass() {
        IgnoreList = new();
    }
}

//In another class
public void LoadDataFromCSV(string Filepath)
{
    var config = new CsvHelper.Configuration.CsvConfiguration(CultureInfo.InvariantCulture)
        {
            MissingFieldFound = null,
            HeaderValidated = null,
        };
    using (var reader = new StreamReader(Filepath))
    using (var csv = new CsvReader(reader, config))
    {
       //***Error on this line***
       var records = csv.GetRecords<MyClass>().ToList();
    }
}

这是一个示例数据行:

Id, DateField
23659961,1/1/2001

CsvHelper 将忽略列表,除非您专门映射它们,因此不需要 IgnoreList 上面的 [Ignore]。您可以在 ClassMap 中使用 Convert 来创建元组。

void Main()
{
    var config = new CsvConfiguration(CultureInfo.InvariantCulture)
    {
    };
    
    using (var reader = new StringReader("Id,DateField1,DateField2\n1,1/5/2022,1/6/2022"))
    using (var csv = new CsvReader(reader, config))
    {
        csv.Context.RegisterClassMap<MyClassMap>();
        var records = csv.GetRecords<MyClass>().Dump();
    }
}

public class MyClass 
{
    public int AwardId { get; set; }

    public List<string> IgnoreList { get; set; }

    public Tuple<DateTime, DateTime> TwoDates { get; set; }

    public MyClass()
    {
        IgnoreList = new();
    }
}

public class MyClassMap : ClassMap<MyClass>
{
    public MyClassMap()
    {
        Map(x => x.AwardId).Name("Id");
        Map(x => x.TwoDates).Convert(args =>
        {
            var value = Tuple.Create(args.Row.GetField<DateTime>("DateField1"), args.Row.GetField<DateTime>("DateField2"));
            
            return value;
        });     
    }
}