jeudi 14 mai 2020

Reference POCO object properties in CsvHelper

I have some nested classes used in generic methods, as defined below;

Base Class:

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

Class 1:

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

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

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". Ideally i'd like to only have ParentFoo.Name. Similarly, when I export an instance of "Bar", I'd like the field "MyFoo" to actually export "MyFoo.Name" as the value.

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;

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?

TIA





Aucun commentaire:

Enregistrer un commentaire