Friday 7 April 2023

Automapper Reverse Mapping: Mapping Objects in Both Directions

AutoMapper is a popular object mapping tool used in .NET applications. It simplifies the process of mapping one object to another by automatically copying properties with matching names and types. Reverse mapping with AutoMapper allows you to create mappings in both directions, from the source object to the destination object and vice versa.

Let's take an example of a simple class Person and its corresponding PersonDto class, which we want to map to each other using AutoMapper.

public class Person

{

    public int Id { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public int Age { get; set; }

}


public class PersonDto

{

    public int Id { get; set; }

    public string FullName { get; set; }

    public int Age { get; set; }

}

Now let's create a mapping from Person to PersonDto:

var config = new MapperConfiguration(cfg =>

{

    cfg.CreateMap<Person, PersonDto>()

        .ForMember(dest => dest.FullName, opt => opt.MapFrom(src => src.FirstName + " " + src.LastName))

        .ReverseMap()

        .ForMember(dest => dest.FirstName, opt => opt.MapFrom(src => src.FullName.Split(' ')[0]))

        .ForMember(dest => dest.LastName, opt => opt.MapFrom(src => src.FullName.Split(' ')[1]));

});


IMapper mapper = config.CreateMapper();


var person = new Person { Id = 1, FirstName = "John", LastName = "Doe", Age = 30 };

var personDto = mapper.Map<PersonDto>(person);


var personDto2 = new PersonDto { Id = 2, FullName = "Jane Smith", Age = 25 };

var person2 = mapper.Map<Person>(personDto2);


In the above code, we first create a mapping from Person to PersonDto and then use the .ReverseMap() method to create a reverse mapping from PersonDto to Person without having to define it explicitly.

With the .ReverseMap() method, we can then use the mapper.Map method to map Person and PersonDto instances in both directions, as shown in the example above.

No comments:

Post a Comment