簡體   English   中英

AutoMapper是否同時支持開放泛型和繼承?

[英]Does AutoMapper support Open Generics and Inheritance at the same time?

我可以看到AutoMapper支持Open GenericsInheritance,但是我無法將其與兩者結合使用。

給定

public class Foo
{
    public int Id { get; set; }
}

public class Bar<T> : Foo
{
    public T Value { get; set; }
}

並假設FooDtoBarDto<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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM