使用接口

时间:2019-07-04 16:44:04

标签: csvhelper

在读取CSV并使用类映射时,出现错误消息“找不到公共无参数构造函数”。我100%确信这是因为我的ClassMap <>中的Class具有一个属性,在我的情况下,该属性是接口 IAddress 。有没有一种方法可以将此属性映射到 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();
}


1 个答案:

答案 0 :(得分:0)

我认为这可能对您有用。

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"])
            });
    }
}