如何配置AutoMapper以全局忽略具有不可访问的设置器(私有或受保护的)的所有属性? [英] How to configure AutoMapper to globally Ignore all Properties With Inaccessible Setter(private or protected)?

查看:67
本文介绍了如何配置AutoMapper以全局忽略具有不可访问的设置器(私有或受保护的)的所有属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不使用IgnoreAllPropertiesWithAnInaccessibleSetter()的情况下自动忽略映射包?

How to Ignore mapping Package automatically without using IgnoreAllPropertiesWithAnInaccessibleSetter() ?

cfg.CreateMap<Dto, InternetContract>();

public class InternetContract
{      

    public virtual string Package { get;protected set; }  
}
public class Dto
{      

    public string Package { get; set; }  
}

推荐答案

从技术上讲,这将满足您的要求:

Technically, this would do what you ask:

    Mapper.Initialize(cfg =>
    {
        cfg.ShouldMapProperty = p =>
        {
            var setMethod = p.GetSetMethod(true);
            return !(setMethod == null || setMethod.IsPrivate || setMethod.IsFamily);
        };
    });

但是,这可能不是您想要的,因为它将忽略整个属性(getter和setter).如果将源InternetContract映射到目标Dto,则Package属性将被忽略,即使它具有公共获取器.我找不到一种方法来全局更改此行为以仅在目标属性为私有/受保护时才应用.这是不幸的.默认情况下,AutoMapper会绕过您已内置到类中的保护,并且没有简便的方法可以在全局范围内更改该默认设置.

However, this is probably not what you want, because it will ignore the entire property (getter and setter). If you are mapping source InternetContract to destination Dto, the Package property will be ignored even though it has a public getter. I could not find a way to globally change this behavior to apply only when the destination property is private/protected. This is unfortunate. AutoMapper will bypass the protections you have built into a class by default, and there is no easy way to change that default globally.

值得注意的是……Jimmy Bogard设计了AutoMapper来从Entity-> Dto进行单向映射,而不是相反.这是有道理的,但是在某些情况下,从Dto-> Entity手动映射每个标准属性会很费力.在这种情况下,AutoMapper仍然可以提供帮助,但是要忽略私有/受保护的设置者,您必须显式地忽略IgnoreAllPropertiesWithAnInaccessibleSetter().

Of note... Jimmy Bogard designed AutoMapper to do one-way mapping from Entity -> Dto, not the other way around. That makes sense, but there are cases where manually mapping every standard property from Dto -> Entity is laborious. AutoMapper can still help in those cases, but to ignore private/protected setters, you'll have to explicitly IgnoreAllPropertiesWithAnInaccessibleSetter().

如果您想使用AutoMapper属性,则可以编写一个包含IgnoreAllPropertiesWithAnInaccessibleSetter()的自定义属性.

If you like to use AutoMapper Attributes, you could write a custom attribute that includes IgnoreAllPropertiesWithAnInaccessibleSetter().

参考文献:

这篇关于如何配置AutoMapper以全局忽略具有不可访问的设置器(私有或受保护的)的所有属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆