我有一个db实体存储像这样的订单地址……
我有像这样的BLL课……
public class DeliveryAddress
{
public string Id { get; set; }
public string PersonyName { get; set; }
public string CompanyName { get; set; }
public List<string> AddressLines { get; set; }
public string Zip { get; set; }
public string City { get; set; }
public string CountryCode { get; set; }
}
和另一个这样的班……
public class InvoiceAddress
{
public string Id { get; set; }
public string PersonyName { get; set; }
public string CompanyName { get; set; }
public List<string> AddressLines { get; set; }
public string Zip { get; set; }
public string City { get; set; }
public string CountryCode { get; set; }
}
我想在AddressType列的基础上将EF实体映射到上面的类.谁能解释我怎么做?
UPDATE
如果addressType是“Delivery”,我想映射到OR.DeliveryAddress,如果addressType是“Invoice”,我想映射到OR.InvoiceAddress
到目前为止,我已经能够做到这一点,但我不知道如何在实体映射级别上应用条件…
Mapper.CreateMap<OrderAddress, OR.DeliveryAddress>()
.ForMember(d => d.City, o => o.MapFrom(s => s.city))
.ForMember(d => d.CompanyName, o => o.UseValue(string.Empty))
.ForMember(d => d.CountryCode, o => o.MapFrom(s => s.countryCode))
.ForMember(d => d.Id, o => o.MapFrom(s => s.id))
.ForMember(d => d.PersonyName, o => o.MapFrom(s => s.name))
.ForMember(d => d.Zip, o => o.MapFrom(s => s.zip));
更新2
与@Yuliam Here is the Fiddle讨论后,我可以提出我的问题……
最佳答案 您可以创建一个客户映射器来对象.此外,您不必使用ForMember指定每个属性,因为如果差异仅为大写/小写(除非为PersonName),默认情况下,AutoMapper在映射属性名称时不区分大小写.
创建对象的自定义映射器.
public class AddressConverter : ITypeConverter<OrderAddress, object>
{
public object Convert(ResolutionContext context)
{
var o = context.SourceValue as OrderAddress;
if (o == null) return null;
if (o.addressType == "Delivery") return Mapper.Map<OR.DeliveryAddress>(o);
if (o.addressType == "Invoice") return Mapper.Map<OR.InvoiceAddress>(o);
return null;
}
}
然后定义映射器.
Mapper.CreateMap<OrderAddress, OR.DeliveryAddress>()
.ForMember(d => d.PersonyName, o => o.MapFrom(s => s.name));
Mapper.CreateMap<OrderAddress, OR.InvoiceAddress>()
.ForMember(d => d.PersonyName, o => o.MapFrom(s => s.name));
Mapper.CreateMap<OrderAddress, object>().ConvertUsing<AddressConverter>();
用法.
var orderAddressDto = Mapper.Map<object>(orderAddress);
实际的orderAddressDto类型将基于addressType.如果OR.DeliveryAddress和OR.InvoiceAddress的接口或基类类型更强.然后用interface / base类替换对象类型.