如何在定义映射后忽略属性

本文关键字:属性 映射 定义 | 更新日期: 2023-09-27 18:07:11

我知道如何在映射定义时忽略属性。但是,我试图为所有映射添加一个公共逻辑,以忽略基于某些条件的属性。对此,我使用如下代码:

public static void ProcessMappings(this IMappingEngine engine)
{
    var typeMaps = engine.ConfigurationProvider.GetAllTypeMaps();
    foreach (var typeMap in typeMaps)
    {
        if (typeof(MyClass).IsAssignableFrom(typeMap.DestinationType)) 
        {
            // here let's say I want to ignore property "Property"
        }
    }
}

所以我的问题是,给定TypeMap的实例,我如何设置一个属性被忽略?

如何在定义映射后忽略属性

var propInfo = typeMap.DestinationType.GetProperty("PropertyToIgnore");
if (propInfo != null)
{
    typeMap.FindOrCreatePropertyMapFor(new  AutoMapper.Impl.PropertyAccessor(propInfo)).Ignore();
}

Ignore方法用于忽略属性/成员