Search code examples
.net-coresystem.reflectioncsvhelperc#-8.0

CSVHelper generic ClassMap with System.Reflection


I'm trying genericly map the properties of my class to the column names of the CSV without the need to write every single line in the ClassMap like

Map(rm => rm.PUsrCrRequestedObject).Name("#P_USR_CR_RequestedObject");

because we have very much columns with mostly the same type of mapping. So i tried the following code:

var classMap = csv.Configuration.AutoMap<RequestMonitoring>();

foreach (var property in typeof(RequestMonitoring).GetProperties())
{
    var columnName = property.Name switch
    {
        "PNdsPn"    => "$P_NDS_PN",
        { } x when x.StartsWith("PUsrCr")   => property.Name.Replace("PUsrCr", "#P_USR_CR_"),
        _           => property.Name
    };
    classMap.Map(requestMonitoring => property).Name(columnName);
}

I don't get an error but if i debug the ClassMap the code above hasn't got any effect.

So the question is how can i fix the code snippet or if it's not possible maybe how to apply the same name conversion for every property


Solution

  • Try this.

    classMap.Map(typeof(RequestMonitoring), property).Name(columnName);