AutoMapper Map如果不为空,否则自定义转换
这是我的代码:
Mapper.CreateMap() .ForMember(dest => dest.Bar, opt => opt.MapFrom(src => src.Bar == null ? new BarViewModel() : src.Bar))
基本上,“BarViewModel”有一个无参数的ctor,可以在类中设置属性。
所以我想对AutoMapper说:
如果值为null,则使用ctor作为类。 否则使用您已有的映射
以上是给我一个C#编译器错误。 而且我猜测演员阵容也不会奏效。
那么有一个AutoMapper技巧吗?
最糟糕的情况我可以删除该属性的映射,只是这样做:
var mapped = Mapper.Map(src); if (mapped.Bar == null) mapped.Bar = new BarViewModel();
但这有点难看。
想法?
您可以使用自定义值解析器 。 以下应该有效:
Mapper.CreateMap() .ForMember(dest => dest.Bar, opt => opt.ResolveUsing(src => src.Bar == null ? new Bar() : Mapper.Map(src.Bar)))
现在,您可以使用.NullSubstitute()
将NULL值替换为.NullSubstitute()
中的某个自定义值,例如:
CreateMap() .ForMember(d => d.myDate, o => o.NullSubstitute(new DateTime(2017,12,12)));
我没有得到以下的编译器错误:
public class Foo { public Bar Bar { get; set; } } public class Foo2 { public Bar Bar { get; set; } } public class Bar { public int Id { get; set; } public Bar() { Id = 3; } } CreateMap() .ForMember( dest => dest.Bar, opt => opt.MapFrom(src => src.Bar == null ? new Bar() : src.Bar));
…所以我想知道问题是否与你的映射实际上没有关系?