这是简单的层次结构:
abstract class Base
{
public int Id { get; set; }
}
class Derived : Base
{
public string Name { get; set; }
}
我需要克隆Derived
个实例,但我想跳过Id
个值。所以,我正在以这种方式配置mapper:
Mapper
.CreateMap<Base, Base>()
.Include<Derived, Derived>()
.ForMember(_ => _.Id, expression => expression.Ignore());
var original = new Derived
{
Id = 1,
Name = "John"
};
var clone = Mapper.Map<Derived>(original);
Console.WriteLine(clone.Id == 0); // writes 'False'
无论是ForMember
调用,都会映射Id
的值。
此配置:
Mapper
.CreateMap<Derived, Derived>()
.ForMember(_ => _.Id, expression => expression.Ignore());
按预期工作,但这不是一个选项,因为它需要为每个派生类型设置ForMember
。
Automapper版本是2.2.1。 我做错了什么?
答案 0 :(得分:1)
您是否尝试Ignore
基类映射上的Id
属性?
Mapper
.CreateMap<Base, Base>()
.ForMember(_ => _.Id, expression => expression.Ignore())
.Include<Derived, Derived>()
.ForMember(_ => _.Id, expression => expression.Ignore());
[...]约定具有更高的优先级,忽略属性 基类映射[...]
https://github.com/AutoMapper/AutoMapper/wiki/Mapping-inheritance