这是简单的层次结构:
abstract class Base
{
public int Id { get; set; }
}
class Derived : Base
{
public string Name { get; set; }
}
我需要克隆Derived
实例,但我想跳过Id
值。所以,我以这种方式配置映射器:
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。我究竟做错了什么?