-3

I have a collection Car including fields for date of production, car name, production place - this is a new model named ProductionPlace including City, Address and Id, and there is another collection in Cars which is Creator - including name, surname and country.

So this basically looks like this

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

How can I map those using CSV Helper? I'm getting "there is no field named Creator" for example. I can simply map fields but not collection nested in my main collection

Edit

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

Both Creator and ProductionPlace are separate models. And Car is a model using those two as it's fields.

San
  • 55
  • 7

1 Answers1

0

Really the only issue you have right now is that both Car and Creator have the same name for the property Name. If you use the CsvHelper name attribute, you can give them different names in your CsvHeader and the rest will map without you having to do anything else.

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; }
}
David Specht
  • 7,784
  • 1
  • 22
  • 30