Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map a collection using CSV Helper

public class Template : Entity
{
    public Template()
    {
        TemplateItems = new List<TemplateItem>();
    }

    public int id { get; set; }
    public string name { get; set; }
    public virtual ICollection<TemplateItem> TemplateItems { get; set; }
}


public class TemplateItem : Entity
{
    public int id { get; set; }
    public int templateId { get; set; }
    public string name { get; set; }
    public virtual Template Template { get; set; }
}


public sealed class TemplateMap : CsvClassMap<Template>
{
    public TemplateMap()
    {
        Map(m => m.name).Name("name");
        //Map(m => m.TemplateItems).ConvertUsing(row => new List<string> { row("nodeType") });

        // How to map a collection value to csv column 
    }
}

I am reading a CSV file and need to map the csv columns to two different tables I have two different models for the tables ie template and templateitem templateitem is mapped from template how to map the csv class ?

like image 320
Richard Avatar asked Feb 25 '26 21:02

Richard


1 Answers

Currently this is not possible. You need to manually handle collections. One way of doing it would be to use ConvertUsing, if you want to keep everything in a mapping file.

Here is an example:

void Main()
{
    using (var stream = new MemoryStream())
    using (var writer = new StreamWriter(stream))
    using (var reader = new StreamReader(stream))
    using (var csv = new CsvReader(reader))
    {
        writer.WriteLine("1,a,b,c");
        writer.WriteLine("2,d,e,f");
        writer.Flush();
        stream.Position = 0;

        csv.Configuration.HasHeaderRecord = false;
        csv.Configuration.RegisterClassMap<TestMap>();
        csv.GetRecords<Test>().Dump();
    }
}

public class Test
{
    public int Id { get; set; }
    public List<string> Names { get; set; } 
}

public class TestMap : CsvClassMap<Test>
{
    public TestMap()
    {
        Map(m => m.Id);
        Map(m => m.Names).ConvertUsing(row =>
        {
            var list = new List<string>();
            list.Add(row.GetField( 1 ));
            list.Add(row.GetField( 2 ));
            list.Add(row.GetField( 3 ));
            return list;
        });
    }
}
like image 140
Josh Close Avatar answered Feb 28 '26 22:02

Josh Close