我有以下抽象类
public abstract class BaseClass
{
public int NumberProperty { get; set; }
}
public abstract class BaseClass_DTO
{
public int NumberProperty { get; set; }
public string NumberPropertyAsString { get; set; }
}
以及以下混凝土等级
public class ConcreteA : BaseClass
{
public string StringProperty { get; set; }
}
public class ConcreteA_DTO : BaseClass_DTO
{
public string StringProperty { get; set; }
}
这是地图
Mapper.Initialize( cfg => {
cfg.CreateMap<BaseClass, BaseClass_DTO>()
.ForMember( p => p.NumberPropertyAsString, opt => opt.MapFrom( x => x.NumberProperty.ToString() ) );
cfg.CreateMap<ConcreteA, ConcreteA_DTO>()
.IncludeBase<BaseClass, BaseClass_DTO>()
.ReverseMap();
} );
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
=============================================================================
ConcreteA_DTO -> ConcreteA (Source member list)
Temporary.Test.ConcreteA_DTO -> Temporary.Test.ConcreteA (Source member list)
Unmapped properties:
NumberPropertyAsString
发生错误的原因是ReverseMap()
调用。如何将反向贴图设置为忽略成员而不复制贴图?
您需要使用忽略反向映射中的NumberPropertyAsString
.ReverseMap()
.ForSourceMember(p => p.NumberPropertyAsString, opt => opt.Ignore());
似乎在您的特定映射配置中,您应该在基础和具体中进行配置。
1.在基类映射中
cfg.CreateMap<BaseClass, BaseClass_DTO>()
.ForMember(p => p.NumberPropertyAsString, opt => opt.MapFrom(x => x.NumberProperty.ToString()))
.ReverseMap()
.ForSourceMember(p => p.NumberPropertyAsString, opt => opt.Ignore());
2.在具体的类映射中
cfg.CreateMap<ConcreteA, ConcreteA_DTO>()
.IncludeBase<BaseClass, BaseClass_DTO>()
.ReverseMap()
.ForSourceMember(p => p.NumberPropertyAsString, opt => opt.Ignore());