使用Automapper将属性名称映射到源中不存在的目标

时间:2010-08-25 19:13:49

标签: automapper

如果我有这样的嵌套源和目标:

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

AddressType是这样的枚举:

public enum AddressType
{
    Billing = 1,
    Shipping = 2,
    Default = 3
};

我设置了这样的地图:

CreateMap<UserInformationViewModel, UserInformation>();

CreateMap<PhysicalAddressViewModel, PhysicalAddress>();

如何让automapper根据正在填充的属性使用正确的枚举填充AddressType。例如,UserInformation.BillingAddress中的PhysicalAddress对象应设置为AddressType.Billing,而UserInformation.ShippingAddress中的PhysicalAddress对象应设置为AddressType.Shipping。

我已经尝试了一切我能想到的工作,但我没有运气。

1 个答案:

答案 0 :(得分:2)

不确定是否有更简单的方法,但如何做以下事情:

    Mapper.CreateMap<UserInformationViewModel, UserInformation>()
        .AfterMap((src,dst)=>dst.BillingAddress.Type = AddressType.Billing)
        .AfterMap((src,dst)=>dst.ShippingAddress.Type = AddressType.Shipping);

您还需要忽略PhysicalAddress中的Type映射

    Mapper.CreateMap<PhysicalAddressViewModel, PhysicalAddress>()
                .ForMember(dst=>dst.Type, opt=>opt.Ignore());