Search code examples
c#asp.net-core-mvcautomapperautomapper-6

Automapper not working in Reverse Mapping with NamingConvention


I’m using Automapper 6.1.1. and need to use reverse mapping. I found bug report from year 2004 and was closed. But in my example is not working, property c12 doesn't have value. So how could I use reverse mapping with this example?

public class Class1
{
    public string COSI_KDESI { get; set; }
}
public class Class2
{
    public string CosiKdesi { get; set; }
}
Mapper.Initialize(cfg =>
{
    cfg.SourceMemberNamingConvention = new LowerUnderscoreNamingConvention();
    cfg.DestinationMemberNamingConvention = new PascalCaseNamingConvention();
    cfg.CreateMap<Class1, Class2>().ReverseMap();
}); 

Class1 c1 = new Class1() { COSI_KDESI = "ttttttt" };

Class2 c2 = Mapper.Map<Class2>(c1);
Class1 c12 = Mapper.Map<Class1>(c2);

Solution

  • You need two different profiles, one configured as you already did and the other reversed.

    Mapper.Initialize(cfg =>
    {
        cfg.CreateProfile("p1", p=>
        {
            p.SourceMemberNamingConvention = new LowerUnderscoreNamingConvention();
            p.CreateMap<Class1, Class2>();
        });
        cfg.CreateProfile("p2", p=>
        {
            p.DestinationMemberNamingConvention = new LowerUnderscoreNamingConvention();
            p.CreateMap<Class2, Class1>();
        });
    });