【问题标题】:Nested collections in CSV Helper mappingCSV Helper 映射中的嵌套集合
【发布时间】:2021-08-16 03:40:40
【问题描述】:

我有一个集合 Car,其中包括生产日期、汽车名称、生产地点的字段 - 这是一个名为 ProductionPlace 的新模型,包括城市、地址和 ID,并且在 Cars 中还有另一个集合是 Creator - 包括姓名、姓氏和国家。

所以这基本上是这样的

Cars
{
ProductionDate,
Name,
ProductionPlace
  {
    Id,
    City,
    Address
  },
Creator
  {
   Name,
   Surname,
   Country
  }

如何使用 CSV Helper 映射那些? 例如,我得到“没有名为 Creator 的字段”。我可以简单地映射字段,但不能映射嵌套在我的主集合中的集合

编辑

My code as far looks like that 

public void MapCar()
{
Map(mapping => mapping.Car).ConvertUsing(
row => { List<Car> car = new List<Car>
{
ProductionDate = row.GetField("ProductionDate"),
Name = row.GetField("Name"),
ProductionPlace = new ProductionPlace
{
Id = row.GetField("Id"),
City = row.GetField("City"),
Address = row.GetField("Address")
},
Creator = new Creator
{
Name = row.GetField("Name"),
Surname = row.GetField("Surname"),
Country = row.GetFiele("Country")
}
};)}

Creator 和 ProductionPlace 都是独立的模型。 Car 是使用这两个字段的模型。

【问题讨论】:

  • 能否请您出示您的代码以便我们进一步帮助您?
  • 当你说“映射那些”时,你到底是什么意思?你期待什么输出?
  • 作为输出,我期待 Car 类型的集合。
  • @San 请展示你的尝试。在上面,这些数据代表什么,一个类,文本等?上面的数据对我所知道的任何事情都无效。
  • @zaggler 我已经更新了我的问题

标签: c# .net mapping csvhelper


【解决方案1】:

您现在真正唯一的问题是CarCreator 的属性Name 具有相同的名称。如果您使用 CsvHelper 名称属性,您可以在您的 CsvHeader 中为它们指定不同的名称,其余的将映射而无需您执行任何其他操作。

void Main()
{
    var input = new StringBuilder();
    input.AppendLine("ProductionDate,CarName,Id,City,Address,CreatorName,Surname,Country");
    input.AppendLine("2021-06-03,Tesla,1,MyCity,MyAddress,Bob,Jones,MyCountry");
    
    using (var reader = new StringReader(input.ToString()))
    using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
    {
        var records = csv.GetRecords<Car>().Dump();
    }
}

public class Car
{
    public DateTime ProductionDate { get; set; }
    [Name("CarName")]
    public string Name { get; set; }
    public ProductionPlace ProductionPlace { get; set; }
    public Creator Creator { get; set; }
}

public class ProductionPlace 
{
    public int Id { get; set; }
    public string City { get; set; }
    public string Address { get; set; }
}

public class Creator
{
    [Name("CreatorName")]
    public string Name { get; set; }
    public string Surname { get; set; }
    public string Country { get; set; }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-12
    • 1970-01-01
    • 2015-02-07
    • 1970-01-01
    • 2016-01-07
    • 2018-01-30
    • 2017-06-11
    • 1970-01-01
    相关资源
    最近更新 更多