如何忽略所有目的地成员,除了被映射的人? [英] How to ignore all destination members, except the ones that are mapped?

查看:158
本文介绍了如何忽略所有目的地成员,除了被映射的人?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法做到这一点?我们有三种不同类型的映射一个SummaryDto,当我们为每种类型创建地图,没有被映射道具抛出一个错误。上有摘要DTO约35的属性。要使用忽略对每一个()选项是太麻烦了。是否有一个全球性的忽视?类似

  CreateMap<信源,目标>()
.IgnoreAllUnmapped();


解决方案

这是为我工作:

 公共静态类MappingExpressionExtensions 
{
公共静态IMappingExpression< TSource,TDest> IgnoreAllUnmapped< TSource,TDest>(这IMappingExpression< TSource,TDest>表达式)
{
expression.ForAllMembers(选择=> opt.Ignore());
返回表达式;
}
}

由于 ForAllMembers 收益无效,要求 ForAllMembers(O = GT; o.Ignore())没有这个扩展方法是行不通的。我们要保持映射表达式可以使后续的映射:

  CreateMap<信源,目的地>()
.IgnoreAllUnmapped()
.ForMember(D => d.Text,O => o.MapFrom(S = GT; s.Name))
.ForMember(D => d.Value ,O => o.MapFrom(S = GT; s.Id));


Is there a way to do this? We have a SummaryDto that maps from three different types, and when we create a map for each type, props that are not mapped are throwing an error. There are about 35 attributes on the summary dto. To use Ignore() option on each one is just too much trouble. Is there a global ignore? Something like

CreateMap<Source,Target>()
   .IgnoreAllUnmapped();

解决方案

This is working for me:

public static class MappingExpressionExtensions
{
    public static IMappingExpression<TSource, TDest> IgnoreAllUnmapped<TSource, TDest>(this IMappingExpression<TSource, TDest> expression)
    {
        expression.ForAllMembers(opt => opt.Ignore());
        return expression;
    }
}

Because ForAllMembers returns void, calling ForAllMembers(o => o.Ignore()) without this extension method wouldn't work. We want to keep the mapping expression available to enable the subsequent mappings:

CreateMap<Source, Destination>()
            .IgnoreAllUnmapped()
            .ForMember(d => d.Text, o => o.MapFrom(s => s.Name))
            .ForMember(d => d.Value, o => o.MapFrom(s => s.Id));

这篇关于如何忽略所有目的地成员,除了被映射的人?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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