Automapper - 忽略IEnumerable <SelectListItem>的所有项目

Gra*_*ler 12 automapper

无论如何,Automapper是否会忽略某种类型的所有属性?我们正在尝试通过验证Automapper映射来提高代码的质量,但是必须.Ignore()为所有IEnumerable<SelectListItem>总是手动创建的代码设置,这会产生摩擦并减慢开发速度.

有任何想法吗?

创建映射后可能的想法:

    var existingMaps = Mapper.GetAllTypeMaps();
    foreach (var property in existingMaps)
    {
        foreach (var propertyInfo in property.DestinationType.GetProperties())
        {
            if (propertyInfo.PropertyType == typeof(List<SelectListItem>) || propertyInfo.PropertyType == typeof(IEnumerable<SelectListItem>))
            {
                property.FindOrCreatePropertyMapFor(new PropertyAccessor(propertyInfo)).Ignore();
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

nem*_*esv 18

Automapper目前不支持基于类型的属性忽略.

目前有三种方法可以忽略属性:

  • Ignore()创建映射时使用选项

    Mapper.CreateMap<Source, Dest>()
        .ForMember(d => d.IgnoreMe, opt => opt.Ignore());
    
    Run Code Online (Sandbox Code Playgroud)

    这是你想要避免的.

  • 使用the注释您的IEnumerable<SelectListItem>属性IgnoreMapAttribute

  • 如果您的IEnumerable<SelectListItem>属性名称遵循一些命名约定.例如,所有这些都以单词开头,"Select"您可以使用该AddGlobalIgnore方法全局忽略它们:

    Mapper.Initialize(c => c.AddGlobalIgnore("Select"));
    
    Run Code Online (Sandbox Code Playgroud)

    但有了这个,你只能匹配开头.

但是,您可以为第一个选项创建一个方便的扩展方法,它会在您调用时自动忽略给定类型的属性CreateMap:

public static class MappingExpressionExtensions
{
    public static IMappingExpression<TSource, TDest> 
        IgnorePropertiesOfType<TSource, TDest>(
        this IMappingExpression<TSource, TDest> mappingExpression,
        Type typeToIgnore
        )
    {
        var destInfo = new TypeInfo(typeof(TDest));
        foreach (var destProperty in destInfo.GetPublicWriteAccessors()
            .OfType<PropertyInfo>()
            .Where(p => p.PropertyType == typeToIgnore))
        {
            mappingExpression = mappingExpression
                .ForMember(destProperty.Name, opt => opt.Ignore());
        }

        return mappingExpression;
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以通过以下方式使用它:

Mapper.CreateMap<Source, Dest>()
    .IgnorePropertiesOfType(typeof(IEnumerable<SelectListItem>));
Run Code Online (Sandbox Code Playgroud)

因此它仍然不是一个全局解决方案,但您不必列出需要忽略的属性,它适用于同一类型的多个属性.

如果你不害怕弄脏你的手:

目前有一个非常hacky的解决方案深入到Automapper的内部.我不知道这个API有多公开,所以这个解决方案可能会在功能中产生影响:

您可以订阅上ConfigurationStoreTypeMapCreated事件

((ConfigurationStore)Mapper.Configuration).TypeMapCreated += OnTypeMapCreated;
Run Code Online (Sandbox Code Playgroud)

并直接在创建的TypeMap实例上添加基于类型的ignore :

private void OnTypeMapCreated(object sender, TypeMapCreatedEventArgs e)
{
    foreach (var propertyInfo in e.TypeMap.DestinationType.GetProperties())
    {
        if (propertyInfo.PropertyType == typeof (IEnumerable<SelectListItem>))
        {
            e.TypeMap.FindOrCreatePropertyMapFor(
                new PropertyAccessor(propertyInfo)).Ignore();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)