AutoMapper ReverseMap in CSharp

Exploring AutoMapper ReverseMap in C#

AutoMapper’s ReverseMap functionality simplifies the creation of reverse mapping configurations, allowing developers to create bi-directional mappings with minimal configuration. This article delves into the usage of ReverseMap in AutoMapper, along with detailed code examples for various scenarios.

Creating Basic ReverseMap

AutoMapper’s ReverseMap method automates the creation of reverse mapping configurations, ensuring seamless bi-directional mapping between source and destination objects.

using AutoMapper;

class Program
{
    static void Main()
    {
        var config = new MapperConfiguration(cfg => {
            cfg.CreateMap<Source, Destination>().ReverseMap();
        });

        IMapper mapper = config.CreateMapper();
        var source = new Source { Value = "Example" };
        var destination = mapper.Map<Destination>(source);

        var reverseMappedSource = mapper.Map<Source>(destination);
        Console.WriteLine(reverseMappedSource.Value); // Output: "Example"
    }
}

class Source
{
    public string Value { get; set; }
}

class Destination
{
    public string Value { get; set; }
}

Customizing ReverseMap

You can customize the ReverseMap configuration to handle specific mapping requirements, enabling precise control over the reverse mapping process.

using AutoMapper;

class Program
{
    static void Main()
    {
        var config = new MapperConfiguration(cfg => {
            cfg.CreateMap<Source, Destination>()
                .ReverseMap()
                .ForMember(dest => dest.Id, opt => opt.Ignore());
        });

        IMapper mapper = config.CreateMapper();
        var source = new Source { Id = 10, Value = "Sample" };
        var destination = mapper.Map<Destination>(source);

        var reverseMappedSource = mapper.Map<Source>(destination);
        Console.WriteLine(reverseMappedSource.Id); // Output: 0
        Console.WriteLine(reverseMappedSource.Value); // Output: "Sample"
    }
}

class Source
{
    public int Id { get; set; }
    public string Value { get; set; }
}

class Destination
{
    public int Id { get; set; }
    public string Value { get; set; }
}

By leveraging AutoMapper’s ReverseMap functionality, developers can effortlessly create bi-directional mapping configurations, ensuring streamlined object mapping between source and destination objects. The ability to customize the ReverseMap configuration further enhances control over the reverse mapping process, catering to specific mapping requirements and ensuring precise object mapping behavior.