1
我正在使用AutoMapper將我自己的複雜類型轉換爲其他Web服務API使用的稍微複雜的類型。使用多態性自動映射覆雜類型?
這裏是我的類型:
namespace Source
{
public class Order
{
public int OrderID { get; set; }
public Client Client { get; set; }
...
}
public class ExistingClient : Client
{
public int ClientID { get; set; }
...
}
public class NewClient : Client
{
public string Name { get; set; }
...
}
}
,我需要這些轉換爲以下
namespace Target
{
public class WebOrder
{
public int OrderID { get; set; }
public WebClient { get; set; }
...
}
public class WebClient
{
public object Item // instance of NewWebClient or ExistingWebClient
}
public class ExistingWebClient
{
public int ClientID { get; set; }
...
}
public class NewWebClient
{
public string Name { get; set; }
...
}
}
我創建了一個AutoMapper輪廓,其中包括以下CreateMap調用(加上一些更多的)
CreateMap<Source.ExistingClient, Target.ExistingWebClient>();
CreateMap<Source.NewClient, Target.NewWebClient>();
CreateMap<Source.Client, Target.WebClient>();
但我被困在如何使用多態性與MapTo()
或ResolveUsing()
正確設置項目屬性,缺少用每個子類型的單獨映射替換最後一行,這似乎笨拙和重複。
CreateMap<Source.NewClient, Target.WebClient>()
.ForMember(d => d.Item, o => o.MapFrom(s =>
Mapper.Map<Source.NewClient, Target.NewWebClient>(s)));
CreateMap<Source.ExistingClient, Target.WebClient>()
.ForMember(d => d.Item, o => o.MapFrom(s =>
Mapper.Map<Source.ExistingClient, Target.ExistingWebClient>(s)));