0

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?

2

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

If the reverse map is not actually needed, of course the first solution is preferable :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.