如何使用自动映射器有条件地将目标对象设置为null [英] How do I conditionally set the destination object to null using automapper

查看:50
本文介绍了如何使用自动映射器有条件地将目标对象设置为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做这样的事情:

I am trying to do something like this:

AutoMapper.Mapper.CreateMap<UrlPickerState, Link>()
        .ForMember(m=>m.OpenInNewWindow,map=>map.MapFrom(s=>s.NewWindow))
        .AfterMap((picker, link) => link = !string.IsNullOrWhiteSpace(link.Url)?link:null) ;

var pickerState = new UrlPickerState();
var linkOutput = AutoMapper.Mapper.Map<Link>(pickerState);

但是, link 的分配值未在任何执行路径中使用.
我希望linkOutput为null,但不是.
我如何使目标对象为空?

However, the assigned value of link is not used in any execution path.
I would like linkOutput to be null, but it is not.
How would I make the destination object null?

有关对象的详细信息:

public class Link
{
    public string Title { get; set; }
    public string Url { get; set; }
    public bool OpenInNewWindow { get; set; }
}

public class UrlPickerState
{
    public string Title { get; set; }
    public string Url { get; set; }
    public bool NewWindow { get; set; }
    //.... etc
}

这是一个小提琴: http://dotnetfiddle.net/hy2nIa

推荐答案

我创建了以下扩展方法来解决此问题.

I created the following extension method to solve this problem.

public static IMappingExpression<TSource, TDestination> PreCondition<TSource, TDestination>(
   this IMappingExpression<TSource, TDestination> mapping
 , Func<TSource, bool> condition
)
   where TDestination : new()
{
   // This will configure the mapping to return null if the source object condition fails
   mapping.ConstructUsing(
      src => condition(src)
         ? new TDestination()
         : default(TDestination)
   );

   // This will configure the mapping to ignore all member mappings to the null destination object
   mapping.ForAllMembers(opt => opt.PreCondition(condition));

   return mapping;
}

对于有问题的情况,可以这样使用:

For the case in question, it can be used like this:

Mapper.CreateMap<UrlPickerState, Link>()
      .ForMember(dest => dest.OpenInNewWindow, opt => opt.MapFrom(src => src.NewWindow))
      .PreCondition(src => !string.IsNullOrWhiteSpace(src.Url));

现在,如果条件失败,则映射器将返回null;否则,映射器将返回null.否则,它将返回映射的对象.

Now, if the condition fails, the mapper will return null; otherwise, it will return the mapped object.

这篇关于如何使用自动映射器有条件地将目标对象设置为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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