0

这是简单的层次结构:

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

4

1 回答 1

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

于 2013-05-27T16:16:01.760 回答