CsvHelper Map Colletion

2019-07-25 13:24发布

问题:

I'm mapping csv file with School records using CsvHelper The end result should be list of Schools. 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; }
}

One of the columns found in the CSV file is SRef which should be linked to 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
        }
    }

I want to map csv file with list of Schools, however one columns is referring to StudentRef so using CSVHelper, how can i achieve that?

回答1:

Use a 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 );
    }
}


标签: c# csvhelper