如何在AutoMapper中全局使用“忽略"? [英] How to use Ignore globally in AutoMapper?

查看:348
本文介绍了如何在AutoMapper中全局使用“忽略"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是现在的样子. DestinationA和DestinationB派生自某些DestinationBase类.我需要忽略所有这些派生类的一些公共属性.无论如何,是否可以全局应用这些忽略选项,而不必对所有派生的目标类重复这些操作?

Here is how it looks like right now. DestinationA and DestinationB are derived from some DestinationBase class. And I need to ignore some common properties for all these derived class. Is there anyway to apply these ignore options globally without having to repeat for all derived destination classes?

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

推荐答案

我遇到了同样的问题,在寻求帮助时遇到了这个老问题.我最终提出了以下解决方案.也许对其他人有帮助...

I had the same issue and came across this old question while searching for help. I ended up coming up with the following solution. Maybe it's helpful to someone else...

我有几个从基类派生的类.我想从该基类派生的任何类的所有映射中排除该基类的属性.创建映射后(并且未指定任何忽略选项),请执行以下操作:

I have several classes derived from a base class. I want to exclude a property of that base class from all mappings of any class that derives from the base. After creating my mappings (and without specifying any ignore options), I do this:

foreach(var map in Mapper.GetAllTypeMaps())
{
    if (typeof(MyBaseClass).IsAssignableFrom(map.DestinationType))
    {
        var propInfo = map.DestinationType.GetProperty("PropertyToIgnore");
        if (propInfo != null) {
            map.FindOrCreatePropertyMapFor(new AutoMapper.Impl.PropertyAccessor(propInfo)).Ignore();
        }
    }
}

这有点蛮力,因为我必须遍历所有类型映射,但这可以完成工作.

It's a little brute force because I have to loop through all the type maps, but it gets the job done.

在if语句中添加了一个缺少的{

edit: Added a missing { to the if statement

这篇关于如何在AutoMapper中全局使用“忽略"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆