![](/img/trans.png)
[英]Does AutoMapper support Open Generics with inheritance from a non-generic base class?
[英]Does AutoMapper support Open Generics and Inheritance at the same time?
我可以看到AutoMapper支持Open Generics和Inheritance,但是我無法將其與兩者結合使用。
給定
public class Foo
{
public int Id { get; set; }
}
public class Bar<T> : Foo
{
public T Value { get; set; }
}
並假設FooDto
和BarDto<T> : FooDto
互補類BarDto<T> : FooDto
則以下行將引發無效的強制轉換異常,表明它無法從FooDto
轉換為BarDto<EntityDto>
Mapper.Map<Bar<Entity>, BarDto<EntityDto>>(AMethodWhichReturnsABar<Entity>());
我嘗試了以下映射:
Mapper.CreateMap<Entity, EntityDto>();
Mapper.CreateMap<Foo, FooDto>();
Mapper.CreateMap(typeof(Bar<>), typeof(BarDto<>));
和
Mapper.CreateMap<Entity, EntityDto>();
Mapper.CreateMap<Foo, FooDto>()
.Include(typeof(Bar<>), typeof(BarDto<>));
Mapper.CreateMap(typeof(Bar<>), typeof(BarDto<>));
兩者都會導致InvalidCastException。 唯一有效的方法是,如果我像這樣顯式映射封閉的泛型:
Mapper.CreateMap<Entity, EntityDto>();
Mapper.CreateMap<Foo, FooDto>();
Mapper.CreateMap<Bar<Entity>, BarDto<EntityDto>>()
很好,但這意味着我將不得不為每個可能具有的封閉通用組合添加一個映射。
這是AutoMapper提供的功能,我做錯了嗎? 還是我為每個需要使用的TI組合添加了映射?
我的問題的答案是肯定的。 令人尷尬的是,我之所以不能,是因為我正在使用AutoMapper 4.0.4進行測試。 使用6.1.1可讓您執行以下操作並按預期工作:
MapperConfiguration config = new MapperConfiguration(c =>
{
c.CreateMap<Entity, EntityDto>();
c.CreateMap(typeof(Foo), typeof(FooDto));
c.CreateMap(typeof(Bar<>), typeof(BarDto<>));;
});
config.AssertConfigurationIsValid();
var mapper = config.CreateMapper();
BarDto<EntityDto> result = mapper.Map<Bar<Entity>, BarDto<EntityDto>>(AMethodWhichReturnsABar<Entity>());
我已經離開了問題並回答了,因為最初是在看的時候,我看不到任何地方明確表明我的要求得到了支持。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.