AutoMapper映射,如果不为空,否则自定义转换 [英] AutoMapper Map If Not Null, Otherwise Custom Convert

查看:317
本文介绍了AutoMapper映射,如果不为空,否则自定义转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

Mapper.CreateMap<Foo, Foo2>()
   .ForMember(dest => dest.Bar, opt => opt.MapFrom(src => src.Bar == null ? new BarViewModel() : src.Bar))

基本上,"BarViewModel"具有无参数ctor,该ctor设置类中的属性.

Basically, "BarViewModel" has a parameterless ctor which sets up properties in the class.

所以我想对AutoMapper说:

So i'm trying to say to AutoMapper:

如果该值为null,则将ctor用于该类.否则,请使用您已有的映射

If the value is null, then use the ctor for the class. otherwise use the mapping you have in place

以上内容为我提供了C#编译器错误.而且我认为演员表也无法正常工作.

The above is giving me a C# compiler error. And i'm guessing a cast wouldn't work either.

那么有没有AutoMapper的技巧可以做到这一点?

So is there a AutoMapper trick to do this?

在最坏的情况下,我可以删除该属性的映射,然后执行以下操作:

Worst case i could remove that mapping for that property, and just do:

var mapped = Mapper.Map<Foo,Foo2>(src);
if (mapped.Bar == null) mapped.Bar = new BarViewModel();

但这有点丑陋.

想法?

推荐答案

您可以使用自定义值解析器.以下应该可以工作:

You can use custom value resolver. The following should work:

Mapper.CreateMap<Foo, Foo2>()
   .ForMember(dest => dest.Bar, opt => opt.ResolveUsing(src => src.Bar == null ? new Bar() : Mapper.Map<Bar,Bar2>(src.Bar)))

这篇关于AutoMapper映射,如果不为空,否则自定义转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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