Search code examples
c#csvhelper

CsvHelper: How to access already mapped class properties within Inline Type Conversion (ConvertUsing)


I was wondering if it is possible to access a property from the mapped class during the mapping process with the CsvReader. Please see the example below.

public class FooCsvMap : ClassMap<FooModel>
{
    public FooCsvMap(BarService barService)
    {
        Map(m => m.BarObject).ConvertUsing(row => barService.Lookup(row.GetField(0)));
        Map(m => m.Bar2).ConvertUsing(row =>
        {
            // ?? Is it possible to access m.BarObject? If yes how?
            var barObject = row.model.BarObject;
        });
    }
}

Solution

  • If you were using CsvWriter you could access BarObject directly.

    var barObject = row.BarObject;
    

    Unfortunately, if you are using CsvReader, I believe you can only access the raw row data because the FooModel object has yet to be created at this point. So you would have to do something like this.

    var barObject = barService.Lookup(row.GetField(0));