Reputation: 199
I would like to know how to map class property when parsing a csv using CsvHelper. For example my csv is like this
Person, John, 53
Address, 123 st, CA90045
and my models are like this
public class Person
{
public string Name {get;set;}
public int Age {get;set;}
public Address Address {get;set;}
}
public class Address
{
public string Street {get;set;}
public string Zip {get;set;}
}
Then how would I set Person.Address to values mapped in Address?
Thanks in advance
Upvotes: 0
Views: 467
Reputation: 112352
Based on the example you linked to, you will have to do some extra processing, as CSV data stores only flat structures. Hierarchical data cannot be represented as in Json or XML.
Assuming that you have done the mapping part right and that an address immediately follows a person on the next CSV-line
var persons = new List<Person>();
Person person;
while (csv.Read())
{
switch (csv.GetField(0))
{
case "Person":
person = csv.GetRecord<Person>();
persons.Add(person);
break;
case "Address":
Address address = csv.GetRecord<Address>();
person.Address = address;
break;
default:
throw new InvalidOperationException("Unknown record type.");
}
}
Upvotes: 1