tags:

views:

24

answers:

1

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.

+1  A: 

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());
Jaime
Great! I think that will work and I'll use it until / unless someone comes up with a better solution. I'll give a day or two, and if there aren't better answers, I'll mark this one.
Brian McCord

related questions