c# - 如何在 AutoMapper 中全局使用忽略?

标签 c# mapping automapper

这是现在的样子。 DestinationA 和 DestinationB 派生自某个 DestinationBase 类。我需要忽略所有这些派生类的一些共同属性。是否可以全局应用这些忽略选项而不必对所有派生目标类重复?

Mapper.CreateMap<SourceA, DestinationA>()
      .ForMember(d => d.PropA, opt => opt.Ignore())
      .ForMember(d => d.PropB, opt => opt.Ignore())
      .ForMember(d => d.PropC, opt => opt.Ignore());

Mapper.CreateMap<SourceB, DestinationB>()
      .ForMember(d => d.PropA, opt => opt.Ignore())
      .ForMember(d => d.PropB, opt => opt.Ignore())
      .ForMember(d => d.PropC, opt => opt.Ignore());

我期待这样的事情:

Mapper.CreateMap<DestinationBase>().ForAllSource()
      .ForMember(d => d.PropA, opt => opt.Ignore())
      .ForMember(d => d.PropB, opt => opt.Ignore())
      .ForMember(d => d.PropC, opt => opt.Ignore());

最佳答案

您可以全局忽略所有未映射的属性。 虽然这与 automapper 的主要优点相矛盾,但只允许进行显式映射: 这是用于 Automapper 6 的:

    var mapperConfiguration = new MapperConfiguration(cfg =>
    {
        cfg.AddProfile(new MyProfile());
        // ignore all unmapped properties globally
        cfg.ForAllMaps((map, exp) => exp.ForAllOtherMembers(opt => opt.Ignore()));
    });

关于c# - 如何在 AutoMapper 中全局使用忽略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8663771/

相关文章:

c# - 事件查看器应用程序崩溃 - 解密错误消息

POJO 的 Java 映射器/修补程序

java - 如何在Hibernate多对多映射中过滤数据

c# - Automapper 映射 Arraylist

C# 使用反射获取通用对象(及其嵌套对象)的属性

c# - CriticalFinalizerObject 用法误区?

c# - Entity Framework 6 从现有表创建模型

python - 优化: Search the best way to compare two list of dict (Python)

c# - AutoMapper 忽略()问题

c# - AutoMapper继承和Linq