用AutoMapper将列表映射到对象

6
我是一个新手,正在使用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; }
}

地址(Address)类如下:

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

这段内容是关于IT技术的翻译:

这个代码可以用于将Membership映射到UserInformationModel,但现在我需要让地址也能正常工作。需要注意的一点是,目标是单个账单地址和单个发货地址,而在原始模型中,所有地址都存储为列表。你可以通过查看RefAddressTypdId和IsPreferredAddress来找到列表中的发货和账单地址。每个RefAddressTypeId只能存在一个首选地址。

那么,我的问题是,如何让AutoMapper执行这种类型的映射?是否可能,还是我最好使用常规映射代码?


我也有完全相同的问题。你找到解决方案了吗?如果是的话,能否请你与我分享一下。我不知道如何使用CustomResolver。如果你能分享一些你的案例示例,那将非常有帮助。 - Rupesh
1个回答

7
您需要使用AutoMapper的自定义值解析器功能。因此,您需要设置一个自定义解析器,使用IsPreferredAddress标志从列表映射到单个实体以找到它。
自定义解析器的文档非常好,您应该可以从中找到答案。

这个功能在投影中无法工作。你有什么解决方法吗? - Interloper

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接