2017-09-13 71 views
1

我可以看到,AutoMapper支持Open GenericsInheritance,但我无法让它与这两者结合使用。AutoMapper是否支持同时打开泛型和继承?

鉴于

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

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

,并假设互补类的FooDtoBarDto<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提供了这个功能吗?我只是做错了吗?或者我坚持为每个我需要使用的组合添加一个映射?

+0

首先让它在没有泛型的情况下工作,然后将它们添加回来,看看你得到了什么。 –

+0

[Here](https://github.com/AutoMapper/AutoMapper/blob/eb1a445b373acfac3895e9fd308c43e070db546e/src/UnitTests/MappingInheritance/ShouldSupportOnlyDestinationTypeBeingDerived.cs)就是一些例子。 –

+0

@LucianBargaoanu如果我删除泛型并将Value属性设置为Entity和EntityDto,那么它可以与我最初尝试的两种映射中的任何一种一起使用。将T加回来导致相同的错误。 – thudbutt

回答

0

我的问题的答案是肯定的。相反,令人尴尬的是我不能这样做的原因是因为我正在使用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>()); 

我已经离开我的问题和回答的,最初的时候我一直在寻找,我看不出任何地方明确指出,我被问到是支持。