使用CsvHelper的referenceMap时出现异常

时间:2014-05-12 08:22:08

标签: csvhelper

我想在csvHelper的帮助下写一个csv文件,但我得到了异常

  

属性' System.String类型**未定义类型System.Collections.Generic.List`1 [ParsingTest1.BookRecord]

我想要实现的结果是像这样的csv文件

05, Henrik, Data
06, Henrik Kodar, 2012
06, Henrik bakar, 2013
05, Fredrik, IT
06, Henrik Kodar, 2012

我查看了quick start reference并问了谷歌先生,但我们找不到原因。我复制了一个我使用的示例代码。

static void Main(string[] args)
{
    var book1 = new BookRecord
    {
        Type = "06",
        Title = "Henrik kodar",
        Year = "2012"
    };

    var book2 = new BookRecord
    {
        Type = "06",
        Title = "Henrik bakar",
        Year = "2013"
    };


    var person = new PersonRecord
    {
        Type = "05",
        Name = "Henrik",
        Profession = "data"
    };

    person.BookRecords.Add(book1);
    person.BookRecords.Add(book2);

    var person1 = new PersonRecord
    {
        Type = "05",
        Name = "Test",
        Profession = "data"
    };

    person1.BookRecords.Add(book1);
    person1.BookRecords.Add(book2);

    var listan = new List<PersonRecord> { person };


    var sr = new StreamWriter(@"C:\Development\bookz.csv");
    var csvWriter = new CsvWriter(sr);
    csvWriter.Configuration.RegisterClassMap<PersonMap>();
    csvWriter.Configuration.RegisterClassMap<BookRecordMap>();
    csvWriter.Configuration.HasHeaderRecord = true;
    csvWriter.WriteRecords(listan);


    sr.Flush();
    sr.Close();
    }
}

public class PersonRecord
{
    public PersonRecord()
    {
        BookRecords = new List<BookRecord>();
    }

    public string Type { get; set; }
    public string Name { get; set; }
    public string Profession { get; set; }
    public List<BookRecord> BookRecords { get; set; }
}

public class BookRecord
{
    public string Type { get; set; }
    public string Title { get; set; }
    public string Year { get; set; }
}

public class PersonMap : CsvClassMap<PersonRecord>
{
    public override void CreateMap()
    {
        Map(m => m.Type).Index(0);
        Map(m => m.Name).Index(1);
        Map(m => m.Profession).Index(2);
        References<BookRecordMap>(m => m.BookRecords);
    }
}

public class BookRecordMap : CsvClassMap<BookRecord>
{
    public override void CreateMap()
    {
        Map(b => b.Type).Index(0);
        Map(b => b.Title).Index(0);
        Map(b => b.Year).Index(1);
    }
}

1 个答案:

答案 0 :(得分:0)

您无法使用映射文件编写IEnumerable。唯一的方法是手动完成。

请参阅:https://stackoverflow.com/a/26151066/68499