Walter Villamizar
Walter Villamizar

Reputation: 3

AutoMapper - Map flatten object to complex object

I have these models:

class Source
{
    String A;
    String B;
    String C;
    String D;
}

class Destination
{
    String A;
    String B;
    Another another;
    Other other;
}

class Other
{
    String C;
    AnotherOne Another;
}

class AnotherOne
{
    String D;
}

I want to map the Source model to Destination and its children. First approach trying using AutoMapper. So is it possible? Or is it better to do this assignment manually?

Upvotes: 0

Views: 620

Answers (1)

Yong Shun
Yong Shun

Reputation: 51125

Solution 1: With ForPath.

var config = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<Source, AnotherOne>();
            
    cfg.CreateMap<Source, Other>()
        .ForPath(dest => dest.Another, opt => opt.MapFrom(src => src));
            
    cfg.CreateMap<Source, Destination>()
        .ForPath(dest => dest.other, opt => opt.MapFrom(src => src));
});

Demo Solution 1 @ .NET Fiddle


Solution 2: With IncludeMembers to flatten and ReverseMap to create the reverse map explicitly.

var config = new MapperConfiguration(cfg =>
{           
    cfg.CreateMap<Source, AnotherOne>()
        .ReverseMap();
            
    cfg.CreateMap<Other, Source>()
        .IncludeMembers(src => src.Another)
        .ReverseMap();
            
    cfg.CreateMap<Destination, Source>()
        .IncludeMembers(src => src.other)
        .ReverseMap();
});

Demo Solution 2 @ .NET Fiddle


References

Flattening (IncludeMembers section) - AutoMapper documentation

Upvotes: 1

Related Questions