简体   繁体   English

使用automapper忽略未使用的属性

[英]Ignore unused properties using automapper

I have a rather large object with lots of properties. 我有一个相当大的对象,有很多属性。

I am using Automapper to map to the properties from a grid. 我正在使用Automapper映射到网格中的属性。

Only a few of the properties need to be mapped and the rest have to be ignored as they are used later not at the time of mapping 只需要映射一些属性,其余的必须被忽略,因为它们以后不在映射时使用

Is there a way to 'Ignore' all of these properties or do I need to write an explicit 'Ignore' for every property - see code below. 有没有办法'忽略'所有这些属性,或者我需要为每个属性写一个明确的'忽略' - 请参阅下面的代码。 I'd like to be able to '.IgnoreAllNotUsed' instead of having to ignore one by one. 我希望能够'.IgnoreAllNotUsed'而不是一个一个地忽略。 Is this possible? 这可能吗?

The class inherits from another class but most of the properties are on the actual class itself link to picture of code 该类继承自另一个类,但大多数属性都在实际类本身链接到代码图片 在此输入图像描述

在此输入图像描述

Just ignore all properties and then specify ForMember. 只需忽略所有属性,然后指定ForMember。 Here is example: 这是一个例子:

var mapping = Mapper.CreateMap<Source, Destination>();
mapping.ForAllMembers(opt=>opt.Ignore());
mapping.ForMember(...)
       .ForMember(...);

You can use this extension method: 您可以使用此扩展方法:

public static void ForAllUnmappedMembers<TSource, TDestination>(
    this IMappingExpression<TSource, TDestination> mapping, 
    Action<IMemberConfigurationExpression<TSource>> memberOptions)
{
    var typeMap = Mapper.FindTypeMapFor<TSource, TDestination>();
    foreach(var memberName in typeMap.GetUnmappedPropertyNames())
        mapping.ForMember(memberName, memberOptions);
}

Use it like this: 像这样使用它:

Mapper.CreateMap<Source, Destination>()
      .ForMember(...)
      .ForAllUnmappedMembers(o => o.Ignore());

I haven't tested it but it should work. 我没有测试过,但它应该工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM