I have a flat POCO Entity and a structured View Model (that is used for rendering a form with custom EditorFor helpers).
Is there any easier way in Automapper 2 to do something like that:
cfg.CreateMap<TelcoDemand, TelcoDemandViewModel>()
.ForMember(d => d.Person, opt => opt.ResolveUsing(s => new PersonViewModel
{
FirstName = s.PersonFirstName,
LastName = s.PersonLastName,
Phone = s.PersonPhone,
Email = s.PersonEmail
}))
.ForMember(d => d.AddressContact, opt => opt.ResolveUsing(s => new AddressViewModel
{
City = s.AddressContactCity,
HouseNumber = s.AddressContactHouseNumber,
Street = s.AddressContactStreet,
Zip = s.AddressContactZip
}))
.ForMember(d => d.AddressCourier, opt => opt.ResolveUsing(s => new AddressViewModel
{
City = s.AddressCourierCity,
HouseNumber = s.AddressCourierHouseNumber,
Street = s.AddressCourierStreet,
Zip = s.AddressCourierZip
}))
.ForMember(d => d.Address, opt => opt.ResolveUsing(s => new AddressViewModel
{
City = s.AddressCity,
HouseNumber = s.AddressHouseNumber,
Street = s.AddressStreet,
Zip = s.AddressZip
}))
What I am trying to achieve is to unflatten Person and Address fields into a viewmodel that then gets rendered using a EditorFor.
Flattening it back to database works great, but there is no way I could get the unflattening working by convention...
Edit
I have also a IgnoreAllUnexisting extension used here, it's implemented like that:
public static IMappingExpression<TSource, TDestination> IgnoreAllNonExisting<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
{
var sourceType = typeof(TSource);
var destinationType = typeof(TDestination);
var existingMaps = Mapper.GetAllTypeMaps().First(x => x.SourceType == sourceType && x.DestinationType == destinationType);
foreach (var property in existingMaps.GetUnmappedPropertyNames())
{
expression.ForMember(property, opt => opt.Ignore());
}
expression.ForAllMembers(opt => opt.Condition(src => !src.IsSourceValueNull));
return expression;
}
Anyway I also tried it without that extension, and the result was just the same - bunch of null values in the complex types.