Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/visual-studio/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 映射派生类型实例时忽略属性_C#_Automapper - Fatal编程技术网

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

C# 映射派生类型实例时忽略属性,c#,automapper,C#,Automapper,以下是简单的层次结构: abstract class Base { public int Id { get; set; } } class Derived : Base { public string Name { get; set; } } 我需要克隆派生的实例,但我想跳过Id值。因此,我以这种方式配置mapper: Mapper .CreateMap<Base, Base>() .Include&

以下是简单的层次结构:

abstract class Base
{
    public int Id { get; set; }
}

class Derived : Base
{
    public string Name { get; set; }
}
我需要克隆
派生的
实例,但我想跳过
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

Automapper版本是2.2.1。
我做错了什么?

您是否尝试忽略基类映射上的
Id
属性

Mapper
    .CreateMap<Base, Base>()
    .ForMember(_ => _.Id, expression => expression.Ignore())
    .Include<Derived, Derived>()
    .ForMember(_ => _.Id, expression => expression.Ignore());
Mapper
.CreateMap()文件
.FormMember(=>389;.Id,表达式=>expression.Ignore())
.包括()
.ForMember(=>u.Id,表达式=>expression.Ignore());
[…]约定具有更高的优先级,该优先级忽略了 基类映射[…]


Include
返回
IMappingExpression
。因此,
IMappingExpression
调用了
ForMember(=>.Id,expression=>expression.Ignore())
。因此,我完全忽略基类映射上的
Id
属性。调用两次
Ignore
(对于
Base
Derived
)是毫无意义的,因为这与为层次结构中的每个类型创建单独的映射相同。不过,您是对的。我更仔细地阅读了映射源。我认为,最后两个(继承的
忽略
和基于约定的)必须交换,但没有人在乎。没想到汽车制造商会做出如此愚蠢的事情。无论如何,谢谢!很高兴知道。我仍然有疑问,甚至可能不根据最后一个优先级点添加第二个
Ignore
:继承的Ignore属性映射
Mapper
    .CreateMap<Base, Base>()
    .ForMember(_ => _.Id, expression => expression.Ignore())
    .Include<Derived, Derived>()
    .ForMember(_ => _.Id, expression => expression.Ignore());