jsuddsjr
jsuddsjr

Reputation: 550

Serializing child classes with csvHelper

I'd like to include values from a child class in my CSV output. The child class contains several Boolean values that indicate available actions.

public class AllowedActions {
    public bool CanCheckIn { get; set; }
    public bool CanCheckOut { get; set; }
}

public class ContentItem {
    public AllowedActions Actions { get; set; }
    public Guid? ContentTypeId { get; set; }
}

Can I create a class map that includes both the ContentItem properties, and the values of the AllowedAction class? Adding them to the map is causing a "Property 'Boolean CanCheckIn' is not defined for type 'XYZ.ContentItem'" error.

This doesn't work:

        Map(m => m.Actions.CanCheckIn);
        Map(m => m.Actions.CanCheckOut);

Upvotes: 4

Views: 3091

Answers (1)

jsuddsjr
jsuddsjr

Reputation: 550

I figured it out. In order to correctly map the members of the child class, I need to use References rather than Map, and provide a separate map object, like so:

        References<AllowedActionsClassMap>(m => m.Actions);

...

public sealed class AllowedActionsClassMap: CsvClassMap<AllowedActions>
{
    public AllowedActionsClassMap()
    {
        Map(m => m.CanCheckIn);
        Map(m => m.CanCheckOut);
    }
}

More information here: CsvHelper Mapping

Upvotes: 7

Related Questions