我正在使用CsvHelper将csv文件映射到学校记录 最终结果应该是学校名单。 Similar issue can be found here
public class School
{
public IList<Student> Students{ get; set; }
}
public class Student
{
public StudentRef Reference{ get; set; }
}
public class StudentRef
{
public string RefNumber{ get; set; }
}
CSV文件中的其中一列是 SRef ,应链接到StudentRef.RefNumber
public sealed class StudentRefMap : CsvClassMap<StudentRef>
{
public StudentRefMap ()
{
Map(m => m.RefNumber).Name("SRef");
}
}
public sealed class StudentMap : CsvClassMap<Student>
{
public StudentMap ()
{
References<StudentRefMap >(m => m.Reference);
}
}
public sealed class SchoolMap : CsvClassMap<School>
{
public SchoolMap ()
{
//References<StudentMap>(m => m.Students);//doesn't work
Map(m => m.Students)
.ConvertUsing(row => new List<Student>
{row.GetRecord<Student>()}); // doesn't work
}
}
我想用Schools
列表映射csv文件,但是有一列是指StudentRef
,所以使用 CSVHelper ,我该如何实现?
答案 0 :(得分:2)
使用ReferenceMap
。 http://joshclose.github.io/CsvHelper/#mapping-reference-map
public sealed class PersonMap : CsvClassMap<Person>
{
public PersonMap()
{
Map( m => m.Id );
Map( m => m.Name );
References<AddressMap>( m => m.Address );
}
}
public sealed class AddressMap : CsvClassMap<Address>
{
public AddressMap()
{
Map( m => m.Street );
Map( m => m.City );
Map( m => m.State );
Map( m => m.Zip );
}
}