Home > Blockchain >  How to reverse map multiple members of an entity that are mapped explicitely in Automapper C#?
How to reverse map multiple members of an entity that are mapped explicitely in Automapper C#?

Time:11-09

I work on a C# app in which I need to map 2 entities. So, I define Create map as below:

CreateMap<Source, Destination>()
                .ForMember(dest => dest.FirstName, map => map.MapFrom(src => src.Name.First))                                                                                           
                .ForMember(dest => dest.LastName, map => map.MapFrom(src => src.Name.Last))
                .ForMember(dest => dest.SSN, map => map.MapFrom(src => src.SSN))
                .ForMember(dest => dest.HomePhoneNo, map => map.MapFrom(src => src.HomePhoneNumber()))
                .ForMember(dest => dest.Address, map => map.MapFrom(src => src.Address))
                .ForMember(dest => dest.MaritalStatus, map => map.MapFrom(src => (int)src.MaritalStatus))

Now, I want to do ReverseMap, but when I add .ReverseMap for each member, in the next line member, the src and dest are switched. So, is there any way to do ReverseMap for all members in just one place?

CodePudding user response:

Put only one ReverseMap() to the end of all custom mappings.

This works for me:

using AutoMapper;

class Program
{
    static void Main(string[] args)
    {            
        var configuration = new MapperConfiguration(cfg =>
        {
            cfg.CreateMap<X, Y>()
            .ForMember(dest => dest.Bar1, map => map.MapFrom(src => src.Foo1))
            .ForMember(dest => dest.Bar2, map => map.MapFrom(src => src.Foo2))
            .ReverseMap()                ;                
        });
        configuration.AssertConfigurationIsValid();
        var mapper = configuration.CreateMapper();
        var x1 = new X() {  Foo1 = "1", Foo2 = "2"};
        var mappedY = mapper.Map<Y>(x1);
        var againX = mapper.Map<X>(mappedY);
        Console.WriteLine($"{againX.Foo1} {againX.Foo2}");
    }
}

class X
{
    public string Foo1 { get; set; }
    public string Foo2 { get; set; }
}

class Y
{
    public string Bar1 { get; set; }
    public string Bar2 { get; set; }
}
  • Related