1
我可以看到,AutoMapper支持Open Generics和Inheritance,但我无法让它与这两者结合使用。AutoMapper是否支持同时打开泛型和继承?
鉴于
public class Foo
{
public int Id { get; set; }
}
public class Bar<T> : Foo
{
public T Value { get; set; }
}
,并假设互补类的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提供了这个功能吗?我只是做错了吗?或者我坚持为每个我需要使用的组合添加一个映射?
首先让它在没有泛型的情况下工作,然后将它们添加回来,看看你得到了什么。 –
[Here](https://github.com/AutoMapper/AutoMapper/blob/eb1a445b373acfac3895e9fd308c43e070db546e/src/UnitTests/MappingInheritance/ShouldSupportOnlyDestinationTypeBeingDerived.cs)就是一些例子。 –
@LucianBargaoanu如果我删除泛型并将Value属性设置为Entity和EntityDto,那么它可以与我最初尝试的两种映射中的任何一种一起使用。将T加回来导致相同的错误。 – thudbutt