Reputation: 550
How do you convert a deep object to a flat object and back using automapper?
for instance:
Person
{
public string Name { get; set; }
public Address Address { get; set; }
}
Address
{
public string City { get; set; }
public string State { get; set; }
}
FlatObject
{
public string Name { get; set; }
public string City { get; set; }
public string State { get; set; }
}
Upvotes: 3
Views: 5212
Reputation: 2414
Starting from version 6.0.1 you can do with the ReverseMap method, wich is used to create the unflatten map.
Mapper
.CreateMap<FlatObject, Person>()
.ReverseMap();
This creates two maps, the flatten map is used to create the reversed one.
There is detailed info at the automapper documentation
Upvotes: 2
Reputation: 126042
Two ways you could accomplish this:
Define two mappings, one from FlatObject --> Person
and another from FlatObject --> Address
:
Mapper.CreateMap<FlatObject, Address>();
Mapper.CreateMap<FlatObject, Person>()
.ForMember(dest => dest.Address, opt => opt.MapFrom(src => src));
Define one mapping and create the Address
object inside the mapping definition:
Mapper.CreateMap<FlatObject, Person>()
.ForMember(
dest => dest.Address,
opt => opt.MapFrom(
src => new Address { City = src.City, State = src.State }));
Personally I'd go with option 1. This way if you add properties to FlatObject
, you won't have to worry about updating the mapping definition (you would if you used option #2).
However, @Raphaël is correct in pointing out the author's link that questions the validity of mapping to domain objects.
Upvotes: 7
Reputation: 60493
Well, AutoMapper is ok for "automatic" flattening, just respect the naming conventions, in your case
FlatObject {
public string Name {get;set;}
public string AddressCity {get;set;}
public string AddressState {get;set;}
}
But AFAIK, AutoMapper doesn't do unflattening .
See this from the author of the library.
They're other tools that do that (with other kinds of limitations), like ValueInjecter
Upvotes: 0