CsvHelper Map Colletion

雨燕双飞 提交于 2019-12-12 22:33:19

问题


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


来源:https://stackoverflow.com/questions/36757299/csvhelper-map-colletion

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!