【发布时间】:2012-12-09 06:23:41
【问题描述】:
我可以在 AutoMapper (v2.2) 中为具有相同 Source 类型但不同 Destination 类型的地图使用继承映射吗?
我有这个基本情况(真正的类有更多的属性):
public abstract class BaseViewModel
{
public int CommonProperty { get; set;}
}
public class ViewModelA : BaseViewModel
{
public int PropertyA { get; set; }
}
public class ViewModelB : BaseViewModel
{
public int PropertyB { get; set; }
}
ViewModelA和ViewModelB是同一个Entity类的不同表示:
public class Entity
{
public int Property1 { get; set; }
public int Property2 { get; set; }
public int Property3 { get; set; }
}
我想为每个 ViewModel 重用 BaseViewModel 的相同映射,例如:
Mapper.CreateMap<Entity, BaseViewModel>()
.Include<Entity, ViewModelA>()
.Include<Entity, ViewModelB>()
.ForMember(x => x.CommonProperty, y => y.MapFrom(z => z.Property1));
Mapper.CreateMap<Entity, ViewModelA>()
.ForMember(x => x.PropertyA, y => y.MapFrom(z => z.Property2));
Mapper.CreateMap<Entity, ViewModelB>()
.ForMember(x => x.PropertyB, y => y.MapFrom(z => z.Property3));
但不幸的是,这似乎不起作用。像这样的调用:
var model = Mapper.Map<Entity, ViewModelA>(entity);
导致model 映射了PropertyA,但没有映射CommonProperty。我相信我正确地遵循了https://github.com/AutoMapper/AutoMapper/wiki/Mapping-inheritance 中的示例,但我担心使用相同的 Source 类型创建多个地图会使 AutoMapper 出错。
有什么见解吗?我喜欢将基类映射分组在一起的想法,但这似乎不起作用。
【问题讨论】:
-
对于这个问题的未来读者 - AutoMapper 似乎已经解决了这个问题。
-
我正在尝试在这里做同样的事情,但我正在尝试做:
var model = Mapper.Map<Entity, BaseViewModel>(entity)但它返回的是 ViewModelA 的实例,而不是 BaseViewModel 的实例,即使我在说Map 函数返回一个 BaseViewModel 类型。我正在使用 Automapper 3.0,看来 2.2 的原始错误已得到解决。 -
这篇 SO 帖子帮助我解决了我的问题,并获得了预期的效果。 stackoverflow.com/questions/27317719/…
标签: c# inheritance automapper automapper-2