How to ignore properties of a specific type when using Automapper?

Deadly 提交于 2019-12-12 15:10:18

问题


Let's suppose that I have two types:

class Type1
{
    public int Prop1 { get; set; }
    public string Prop2 { get; set; }
    public string Prop3 { get; set; }
}

class Type2
{
    public int Prop1 { get; set; }
    public string Prop2 { get; set; }
    public TypeToIgnore Prop3 { get; set; }
}

I want to map between these two types, but ignoring all the properties that have a TypeToIgnore. This is because I am iterating through all of them using reflection and make some custom mappings on them.

Within a class which derives from Profile, I could add an Ignore for each member that I don't want to be mapped, like this:

CreateMap<Type2, Type1>().ForMember(x => x.Prop3, y => y.Ignore());

Or I could use the IgnoreMapAttribute on the properties to be ignored, but considering that on the production code, I have plenty of them, is there a much easier way to ignore some specific types at all?


回答1:


You can use ShouldMapProperty in your config:

 cfg.ShouldMapProperty = p => p.PropertyType != typeof(string);

Official docs on this here. Original feature request by yours truly.



来源:https://stackoverflow.com/questions/54771491/how-to-ignore-properties-of-a-specific-type-when-using-automapper

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