问题
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