映射派生类型实例时忽略属性

时间:2013-05-27 13:49:54

标签: c# automapper

这是简单的层次结构:

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。 我做错了什么?

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