Mapping from list down to object with AutoMapper

I'm new with AutoMapper and have a problem I'm trying to solve.

If I have a source class like this:

public class Membership
{
    public int MembershipId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string OrganizationName { get; set; }
    public List<Address> Addresses { get; set; }
}

And the Address class looks like this:

public class Address
{
    public int AddressId{ get; set; }
    public int RefAddressTypeId { get; set; }
    public string AddressLine1 { get; set; }
    public string AddressLine2 { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Zip { get; set; }
    public bool IsPreferredAddress { get; set; }
}

My destination class is:

public class UserInformationModel
{
    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; }
}

And the destination address class is:

public class PhysicalAddress
{
    public AddressType AddressType{get; set;}
    public string AddressLine1 { get; set; }
    public string AddressLine2 { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string PostalCode { get; set; }

}

I have set up a mapping like this:

Mapper.CreateMap<MinistryMattersIntegration.BusinessObjects.Entities.Cokesbury.Membership, UserInformationModel>()
      .ForMember(dest => dest.Organization, opt => opt.MapFrom(src=>src.OrganizationName));

This is working for Membership to UserInformationModel, but now I need to get addresses working. One important thing to note, though, is that the destination is a single billing address and a single shipping address while in the original model, all the address are stored as a list. The way you find the shipping and billing addresses out of the list is by looking at the RefAddressTypdId and the IsPreferredAddress. Only one preferred address may exist with a particular RefAddressTypeId.

So, my question is, how do you get AutoMapper to do this kind of mapping? Is it possible, or am I better off just going with regular mapping code?


You'll want to use the Custom Value Resolvers feature of AutoMapper. So you'd setup a Custom Resolver to map from your list to your single entity using the IsPreferredAddress flag to find it.

The documentation is pretty good for the Custom Resolvers so you should be fine figuring it out from there.

链接地址: http://www.djcxy.com/p/37366.html

上一篇: 使用AutoMapper复制列表项目

下一篇: 使用AutoMapper从列表向下映射到对象