【问题标题】:Mapping from list down to object with AutoMapper使用 AutoMapper 从列表映射到对象
【发布时间】:2010-08-12 19:35:39
【问题描述】:

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

这适用于 UserInformationModel 的成员资格,但现在我需要让地址正常工作。不过,需要注意的重要一点是,目的地是一个账单地址和一个送货地址,而在原始模型中,所有地址都存储为一个列表。从列表中查找送货地址和帐单地址的方法是查看 RefAddressTypdId 和 IsPreferredAddress。一个特定的 RefAddressTypeId 只能存在一个首选地址。

所以,我的问题是,如何让 AutoMapper 进行这种映射?有可能吗,还是我最好使用常规映射代码?

【问题讨论】:

  • 我也有完全相同的问题。您找到问题的解决方案了吗?如果是,那么您能否与我分享。我不知道如何使用 CustomResolver。如果你能分享一些你的案例的例子,那将非常有帮助。

标签: automapper


【解决方案1】:

您需要使用 AutoMapper 的 Custom Value Resolvers 功能。因此,您需要设置一个自定义解析器,以使用 IsPreferredAddress 标志从列表映射到您的单个实体来查找它。

文档对于自定义解析器来说非常好,所以你应该可以从那里弄清楚。

【讨论】:

  • 此功能不适用于投影。你有什么解决方法吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-16
  • 2012-10-16
  • 2019-04-26
  • 1970-01-01
  • 1970-01-01
  • 2011-05-15
相关资源
最近更新 更多