这是我的代码:
Mapper.CreateMap<Foo, Foo2>()
.ForMember(dest => dest.Bar, opt => opt.MapFrom(src => src.Bar == null ? new BarViewModel() : src.Bar))
基本上,“BarViewModel”有一个无参数的构造函数,它在类中设置属性。
所以我想对 AutoMapper 说:
If the value is null, then use the ctor for the class. otherwise use the mapping you have in place
以上是给我一个 C# 编译器错误。我猜类型转换也行不通。
那么有没有 AutoMapper 技巧可以做到这一点?
最坏的情况是我可以删除该属性的映射,然后:
var mapped = Mapper.Map<Foo,Foo2>(src);
if (mapped.Bar == null) mapped.Bar = new BarViewModel();
但这有点丑。
想法?
最佳答案
您可以使用 custom value resolver .以下应该有效:
Mapper.CreateMap<Foo, Foo2>()
.ForMember(dest => dest.Bar, opt => opt.ResolveUsing(src => src.Bar == null ? new Bar() : Mapper.Map<Bar,Bar2>(src.Bar)))
关于c# - AutoMapper 映射如果不为空,否则自定义转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11555721/