使用接口时未找到 public 无参数构造函数

No public parameterless constructor found when using Interface

当读取我的 CSV 文件并使用 class 地图时,我收到一条错误消息说 "No public parameterless constructor found." 我 100% 确定这是因为我的 Class 在我的 Class 地图中<> 有一个 属性,在我的例子中是一个接口 IAddress。有没有一种方法可以将此 属性 映射到 class 实现,即 Address?

我试过像这样使用参考地图 References(m => m.Address, mappings);

这是我的代码(为简洁起见省略了一些属性):


  public class Customer
  {
    public int Id { get; set; }

    public IAddress CurrentAddress { get; set; }

    public Customer()
    {
    }
  }

  public sealed class CustomerMap : ClassMap<Customer>
  {
      public CustomerMap(Dictionary<string, string> mappings)
      {
          References<AddressMappings>(m => m.CurrentAddress, mappings);
      }
  }

 public class AddressMappings : ClassMap<IAddress>
 {
     public AddressMappings(Dictionary<string, string> mappings)
     {
         Map(m => m.FlatNumber).Name(mappings["FlatNumber"]);
         Map(m => m.PropertyNumber).Name(mappings["PropertyNumber"]);
         Map(m => m.PropertyName).Name(mappings["PropertyName"]);
         Map(m => m.AddressLine1).Name(mappings["AddressLine1"]);
         Map(m => m.AddressLine2).Name(mappings["AddressLine2"]);
         Map(m => m.AddressLine3).Name(mappings["AddressLine3"]);
         Map(m => m.Town).Name(mappings["Town"]);
         Map(m => m.City).Name(mappings["City"]);
         Map(m => m.Ward).Name(mappings["Ward"]);
         Map(m => m.Parish).Name(mappings["Parish"]);
         Map(m => m.County).Name(mappings["County"]);
         Map(m => m.Country).Name(mappings["Country"]);
         Map(m => m.Postcode).Name(mappings["Postcode"]);
     }
 }

using (var reader = new StreamReader(filePath))
using (var csv = new CsvReader(reader))
{
    csv.Configuration.Delimiter = ",";
    var mappingObject = new CustomerMap(mappings);
    csv.Configuration.RegisterClassMap(mappingObject);
    var records = csv.GetRecords<Customer>();
    return records?.ToList();
}


我认为这可能适合你。

public sealed class CustomerMap : ClassMap<Customer>
{
    public CustomerMap(Dictionary<string, string> mappings)
    {
        Map(m => m.CurrentAddress).ConvertUsing(row => 
            new Address {
                FlatNumber = row.GetField<int>(mappings["FlatNumber"]),
                PropertyNumber = row.GetField<int>(mappings["PropertyNumber"]),
                AddressLine1 = row.GetField(mappings["AddressLine1"]),
                AddressLine2 = row.GetField(mappings["AddressLine2"]),
                AddressLine3 = row.GetField(mappings["AddressLine3"]),
                Town = row.GetField(mappings["Town"]),
                City = row.GetField(mappings["City"]),
                Ward = row.GetField(mappings["Ward"]),
                Parish = row.GetField(mappings["Parish"]),
                County = row.GetField(mappings["County"]),
                Country = row.GetField(mappings["Country"]),
                Postcode = row.GetField(mappings["Postcode"])
            });
    }
}