c# - AutoMapper 映射如果不为空,否则自定义转换

标签 c# automapper

这是我的代码:

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/

相关文章:

c# - SharePoint 获取内容类型名称

c# - 从双映射

c# - 是否可以使用枚举动态获取静态类?

c# - 当一个方法使用缓存,但偶尔会做 I/O 时,它应该返回 T 还是 Task<T>?

c# - Automapper 自定义内联映射

c# - 我什么时候应该使用 AutoMapper,什么时候不应该

mapping - Automapper - 嵌套实体

Automapper 将源列表项附加到目标列表

c# - C# 是否具有运行时分配的 goto?

在 32 位和 64 位 Linux 中使用 long 的 C# pInvoke :