简体   繁体   English

参考 CsvHelper 中的 POCO object 属性

[英]Reference POCO object properties in CsvHelper

I have some nested classes used in generic methods, as defined below;我有一些在泛型方法中使用的嵌套类,如下定义;

Base Class:基础 Class:

public class Model
{
public int Id {get; set; }
public string Name {get; set; }
}

Class 1: Class 1:

public class Foo: Model
{
public string Description {get; set; }

    [Name("Parent")]
    [HeaderPrefix("z_Parent")]
public Foo ParentFoo {get; set; }
}

Class 2: Class 2:

public class Bar: Model
{
public Foo MyFoo {get; set; }
}

When i export to CSV an instance of Foo, I get the fields from both the "Foo" instance i've passed in, as well as all of the fields from "ParentFoo".当我将 Foo 的一个实例导出到 CSV 时,我会从我传入的“Foo”实例以及“ParentFoo”的所有字段中获取字段。 Ideally i'd like to only have ParentFoo.Name.理想情况下,我只想拥有 ParentFoo.Name。 Similarly, when I export an instance of "Bar", I'd like the field "MyFoo" to actually export "MyFoo.Name" as the value.同样,当我导出“Bar”的实例时,我希望字段“MyFoo”实际导出“MyFoo.Name”作为值。

I've tried playing around with the configuration options, and all i can think is to set the class to ignore the references, which works in that all of the parent fields aren't included, but also the reference to the parent is also missing;我尝试过使用配置选项,我能想到的就是将 class 设置为忽略引用,这在不包括所有父字段的情况下起作用,而且对父字段的引用也丢失了;

var csv = new CsvWriter(writeFile, CultureInfo.InvariantCulture);
csv.Configuration.IgnoreReferences = true;
csv.WriteRecords(Items);

Is there a way to achieve this, or should I look into writing my own CSV exporter?有没有办法实现这一点,或者我应该考虑编写自己的 CSV 导出器?

TIA TIA

You could use a ClassMap .您可以使用ClassMap

public sealed class FooClassMap : ClassMap<Foo>
{
    public FooClassMap()
    {
        Map(m => m.Id);
        Map(m => m.Name);
        Map(m => m.Description);
        Map(m => m.ParentFoo.Name).Name("ParentName");
    }
}
var csv = new CsvWriter(writeFile, CultureInfo.InvariantCulture);
csv.Configuration.RegisterClassMap<FooClassMap>();
csv.WriteRecords(Items);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM