ViewModel:
Class BaseViewModel
{
public string ViewOnlyProperty{get; set;}
...
}
Class VmClass<T,A>:BaseViewModel where T:IVmShared A:IVmSpecific
{
...
}
DomainModel:
Class BaseDomainModel
{
...
}
Class DomainClass<T,A>:BaseDomainModel where T:IDomainShared A:IDomainSpecific
{
...
}
Automapper:
Mapper.CreateMap<BaseDomainModel, BaseViewModel>()
.Include<IDomainClass<IDomainShared,IDomainSpecific>, VmClass<IVmShared,IVmSpecific>>()
// Included other concrete classes implements Domain and View models interfaces
.ForMember(x => x.ViewOnlyProperty, opt => opt.Ignore());
Mapper.CreateMap<IDomainClass<IDomainShared,IDomainSpecific>, VmClass<IVmShared,IVmSpecific>>()
.ForMember(x => x.ViewOnlyProperty, opt => opt.Ignore()).ReverseMap();
我对ViewModel到域映射具有相同的配置。但是我在Mapper.AssertConfigurationIsValid();
Unmapped members were found. Review the types and members below.
Add a custom mapping expression, ignore, add a custom resolver, or modify the source/destination type
VmClass`2 -> DomainClass`2 (Source member list)
VmClass`2[[IVmShared],[IVmSpecific]] -> DomainClass`2[[IDomainShared],[IDomainSpecific]] (Source member list)
---------------------------------------------------------------------------------------
ViewOnlyProperty
为什么我在viewmodel属性验证viewModel-&gt; DomainModel映射时遇到异常,其中目标在基类中根本没有这个属性?
答案 0 :(得分:0)
我找到了这个问题的原因。那是:
Mapper.CreateMap<IDomainClass<IDomainShared,IDomainSpecific>, VmClass<IVmShared,IVmSpecific>>()
.ForMember(x => x.ViewOnlyProperty, opt => opt.Ignore()).ReverseMap();
ReverseMap()不起作用,因为目标中不存在ViewOnlyProperty。但Automapper试图将“ViewOnlyProperty”从域映射到视图模型,因为反向映射是在同一个CreateMap()上完成的。通过将映射拆分为:
来解决问题 Mapper.CreateMap<IDomainClass<IDomainShared,IDomainSpecific>, VmClass<IVmShared,IVmSpecific>>()
.ForMember(x => x.ViewOnlyProperty, opt => opt.Ignore());
Mapper.CreateMap<VmClass<IVmShared,IVmSpecific>,IDomainClass<IDomainShared,IDomainSpecific>>();