gpt4 book ai didi

Automapper - 忽略 IEnumerable 的所有项目

转载 作者:行者123 更新时间:2023-12-04 00:44:50 24 4
gpt4 key购买 nike

无论如何,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();
}
}
}

最佳答案

Automapper 当前不支持基于类型的属性忽略。

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

  • 使用 Ignore()创建映射时的选项
    Mapper.CreateMap<Source, Dest>()
    .ForMember(d => d.IgnoreMe, opt => opt.Ignore());

    这是你想要避免的。
  • 在您的 IEnumerable<SelectListItem> 上批注与 IgnoreMapAttribute 的属性
  • 如果您的 IEnumerable<SelectListItem>属性名称遵循一些命名约定。例如所有这些都以 "Select" 开头您可以使用 AddGlobalIgnore全局忽略它们的方法:
    Mapper.Initialize(c => c.AddGlobalIgnore("Select"));

    但是有了这个,您只能与开头匹配。

  • 但是,您可以为第一个选项创建一个方便的扩展方法,当您调用 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;
    }
    }

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

    Mapper.CreateMap<Source, Dest>()
    .IgnorePropertiesOfType(typeof(IEnumerable<SelectListItem>));

    所以它仍然不会是一个全局解决方案,但您不必列出需要忽略哪些属性,它适用于同一类型的多个属性。

    如果你不怕弄脏你的手:

    目前有一个非常hacky的解决方案,它深入到Automapper的内部。我不知道这个 API 有多公开,所以这个解决方案可能会阻止这个功能:

    您可以订阅 ConfigurationStoreTypeMapCreated事件

    ((ConfigurationStore)Mapper.Configuration).TypeMapCreated += OnTypeMapCreated;

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

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

    关于Automapper - 忽略 IEnumerable<SelectListItem> 的所有项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15337883/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com