简体   繁体   English

自动映射器配置忽略目标类的基成员

[英]Automapper configuration to ignore a destination class's base member

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();

I have the same configurations for ViewModel to Domain mappings. 对于ViewModel到Domain的映射,我具有相同的配置。 But I am getting the below exception after Mapper.AssertConfigurationIsValid(); 但是我在Mapper.AssertConfigurationIsValid();之后收到以下异常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

Why I am getting exception for viewmodel property when it's validating viewModel->DomainModel mapping, where destination doesn't have this property at all in the base class? 为什么在验证viewModel-> DomainModel映射时,viewmodel属性出现异常,而目的地在基类中根本没有此属性?

I have found the cause for this issue. 我已找到此问题的原因。 It was: 它是:

 Mapper.CreateMap<IDomainClass<IDomainShared,IDomainSpecific>, VmClass<IVmShared,IVmSpecific>>()
.ForMember(x => x.ViewOnlyProperty, opt => opt.Ignore()).ReverseMap();

ReverseMap() doesn't work as ViewOnlyProperty doesn't exist in the destination. ReverseMap()无效,因为目标中不存在ViewOnlyProperty。 But Automapper was trying to map the "ViewOnlyProperty" from domain to view model, because of the reverse mapping was done on the same CreateMap(). 但是Automapper试图将“ ViewOnlyProperty”从域映射到视图模型,因为反向映射是在同一CreateMap()上完成的。 Issue is fixed by splitting the mapping to: 通过将映射拆分到以下位置可解决问题:

 Mapper.CreateMap<IDomainClass<IDomainShared,IDomainSpecific>, VmClass<IVmShared,IVmSpecific>>()
.ForMember(x => x.ViewOnlyProperty, opt => opt.Ignore());

 Mapper.CreateMap<VmClass<IVmShared,IVmSpecific>,IDomainClass<IDomainShared,IDomainSpecific>>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM