Mapping to a destination that doesn't exist in the source based on propery name with Automapper
If I have a nested source and destination like this:
public class UserInformationViewModel
{
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Organization { get; set; }
public string EmailAddress { get; set; }
public PhysicalAddressViewModel BillingAddress { get; set; }
public PhysicalAddressViewModel ShippingAddress { get; set; }
}
public class PhysicalAddressViewModel
{
public string Line1 { get; set; }
public string Line2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }
}
public class UserInformation
{
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Organization { get; set; }
public string EmailAddress { get; set; }
public PhysicalAddress BillingAddress { get; set; }
public PhysicalAddress ShippingAddress { get; set; }
}
public class PhysicalAddress
{
public AddressType Type { get; set; }
public string Line1 { get; set; }
public string Line2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }
}
And AddressType is an enum like this:
public enum AddressType
{
Billing = 1,
Shipping = 2,
Default = 3
};
And I have setup Maps like this:
CreateMap<UserInformationViewModel, UserInformation>();
CreateMap<PhysicalAddressViewModel, PhysicalAddress>();
How can I get automapper to populate AddressType with the proper enum based on the property that is being populated. For example, the PhysicalAddress object that is in UserInformation.BillingAddress should be set to AddressType.Billing while the PhysicalAddress object that is in UserInformation.ShippingAddress should be开发者_运维知识库 set to AddressType.Shipping.
I've tried everything I can think of to make this work, but I haven't had any luck.
Not sure if there's an easier way, but how about doing something like:
Mapper.CreateMap<UserInformationViewModel, UserInformation>()
.AfterMap((src,dst)=>dst.BillingAddress.Type = AddressType.Billing)
.AfterMap((src,dst)=>dst.ShippingAddress.Type = AddressType.Shipping);
You will need to ignore the Type mapping in the PhysicalAddress also
Mapper.CreateMap<PhysicalAddressViewModel, PhysicalAddress>()
.ForMember(dst=>dst.Type, opt=>opt.Ignore());
精彩评论