映射繼承(Mapping Inheritance)
映射繼承有兩個功能:
- 從基類或接口配置繼承映射配置
- 運行時多態(tài)映射
繼承的配置是可選擇的劫拗,你可以在基類中使用Include
來指定可被繼承的映射配置或者在派生類使用IncludeBase
來指定:
CreateMap<BaseEntity, BaseDto>()
.Include<DerivedEntity, DerivedDto>()
.ForMember(dest => dest.SomeMember, opt => opt.MapFrom(src => src.OtherMember));
CreateMap<DerivedEntity, DerivedDto>();
或者
CreateMap<BaseEntity, BaseDto>()
.ForMember(dest => dest.SomeMember, opt => opt.MapFrom(src => src.OtherMember));
CreateMap<DerivedEntity, DerivedDto>()
.IncludeBase<BaseEntity, BaseDto>();
在上面的情況中间校,派生的映射繼承于基礎映射配置中的自定義映射配置。
運行時多態(tài)
用法:
public class Order { }
public class OnlineOrder : Order { }
public class MailOrder : Order { }
public class OrderDto { }
public class OnlineOrderDto : OrderDto { }
public class MailOrderDto : OrderDto { }
Mapper.Initialize(cfg => {
cfg.CreateMap<Order, OrderDto>()
.Include<OnlineOrder, OnlineOrderDto>()
.Include<MailOrder, MailOrderDto>();
cfg.CreateMap<OnlineOrder, OnlineOrderDto>();
cfg.CreateMap<MailOrder, MailOrderDto>();
});
// 執(zhí)行映射
var order = new OnlineOrder();
var mapped = Mapper.Map(order, order.GetType(), typeof(OrderDto));
Assert.IsType<OnlineOrderDto>(mapped);
需要映射的對象是OnlineOrder
杨幼,AutoMapper
找到一個比OrderDto
更具體的OnlineOrder
映射撇簿,就自動選擇了OnlineOrder
。
在派生類中指定繼承
你可以使用在派生類中指定需要繼承的映射來代替在基類中配置需要被繼承的映射:
Mapper.Initialize(cfg => {
cfg.CreateMap<Order, OrderDto>()
.ForMember(o => o.Id, m => m.MapFrom(s => s.OrderId));
cfg.CreateMap<OnlineOrder, OnlineOrderDto>()
.IncludeBase<Order, OrderDto>();
cfg.CreateMap<MailOrder, MailOrderDto>()
.IncludeBase<Order, OrderDto>();
});
繼承映射優(yōu)先級
一個屬性有多種映射途徑差购,它們的優(yōu)先級如下:
- 顯式映射 (使用 .MapFrom())
- 繼承的顯式映射
- 忽略屬性映射
- 轉換映射 (匹配的通過轉換的屬性)
為了演示四瘫,我們修改上面顯示的類
//域對象
public class Order { }
public class OnlineOrder : Order
{
public string Referrer { get; set; }
}
public class MailOrder : Order { }
//數(shù)據(jù)傳輸對象
public class OrderDto
{
public string Referrer { get; set; }
}
//映射
Mapper.Initialize(cfg => {
cfg.CreateMap<Order, OrderDto>()
.Include<OnlineOrder, OrderDto>()
.Include<MailOrder, OrderDto>()
.ForMember(o=>o.Referrer, m=>m.Ignore());
cfg.CreateMap<OnlineOrder, OrderDto>();
cfg.CreateMap<MailOrder, OrderDto>();
});
// 執(zhí)行映射
var order = new OnlineOrder { Referrer = "google" };
var mapped = Mapper.Map(order, order.GetType(), typeof(OrderDto));
Assert.Equals("google", mapped.Referrer);
請注意,在的映射配置中欲逃,我們忽略了Referrer
(因為在order的基類中找不到)找蜜,而且它有一個更高優(yōu)先級的轉換映射,所以這個成員沒有被映射稳析。
總得來說洗做,這個特征使得AutoMapper
使用繼承變得更自然。