How to configure AutoMapper to globally Ignore all Properties With Inaccessible Setter(private or protected)?

余生长醉 提交于 2021-02-08 02:57:49

问题


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; }  
}

回答1:


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);
        };
    });

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.

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().

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

References:

  • Configuring visibility
  • HasAnInaccessibleSetter()
  • The case for two-way mapping in AutoMapper
  • Using AutoMapper with Attributes


来源:https://stackoverflow.com/questions/39752335/how-to-configure-automapper-to-globally-ignore-all-properties-with-inaccessible

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!