Reputation: 3
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
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));
});
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();
});
References
Flattening (IncludeMembers section) - AutoMapper documentation
Upvotes: 1