2010-08-12 162 views
5

我是新的AutoMapper,並有一個問題,我試圖解決。從列表映射到AutoMapper的對象

如果我有一個源類是這樣的:

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; } 
} 

和地址類看起來是這樣的:

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; } 
} 

我的目的地類是:

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; } 
} 

和目標地址類是:

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; } 

} 

我已經建立了一個這樣的映射:

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

這正在爲會員,以UserInformationModel,但現在我需要地址的工作。但是,需要注意的一點是,目標地址是單個帳單地址和單個送貨地址,而在原始模型中,所有地址均以列表形式存儲。您從列表中找到運輸和帳單地址的方式是查看RefAddressTypdId和IsPreferredAddress。特定的RefAddressTypeId只能存在一個首選地址。

所以,我的問題是,你如何得到AutoMapper做這種映射?是否有可能,還是我更適合使用常規的映射代碼?

+0

我也有完全類似的問題。你有沒有找到你的問題的解決方案?如果是,那麼你可以請與我分享。我不知道如何使用CustomResolver。如果你能分享一些你的案例,這將是非常有益的。 – Rupesh 2013-10-08 13:51:45

回答

6

你會想要使用AutoMapper的Custom Value Resolvers功能。因此,您需要設置一個自定義解析器,使用IsPreferredAddress標誌將您的列表映射到您的單個實體。

該文檔對於自定義分解器非常有用,因此您應該很好地從中找出它。