AutoMapper对NULL的优雅处理



我正在将一个嵌套很深的实体映射到一个扁平的Dto对象,我想知道如何使用AutoMapper优雅地处理这个问题。我知道我可以在映射每个属性时对其进行null检查,但对于这样的东西来说,这会变得非常糟糕

ForMember(s => s.Property, o => o.MapFrom(s => s.Parent.Child1.Child2.Child3.Property)

所以我想我可以使用不同的映射配置到同一个目标对象。。。但由于对AutoMapper相对不熟练,我不确定这会对性能产生什么影响。我还有什么更好的方法来实现我想要的?

为了重新迭代,我希望避免这样的事情(我知道下面的代码可能不会编译……这只是一个例子),我必须为每个成员这样做:

ForMember(s => s.Property, o => o.MapFrom(
    s => s.Parent == null ? string.Empty :
    s => s.Parent.Child1 == null ? string.Empty :
    s => s.Parent.Child1.Child2 == null ? string.Empty :
    s => s.Parent.Child1.Child2.Child3 == null ? string.Empty :
    s => s.Parent.Child1.Child2.Child3.Property));

我认为AutoMapper实际上会自动为您处理这样的null传播。你的例子:

ForMember(s => s.Property, o => o.MapFrom(s => s.Parent.Child1.Child2.Child3.Property)

如果任何中间成员是null,则应解析为null(I认为)。

示例:https://dotnetfiddle.net/hMo3wa

虽然这适用于单个实例,但不适用于可查询集合上的Projections。

我添加到Andrew答案中的这个附加代码失败得很惨,即使在最新的5.1.1版本中也是如此。

    var list = new List<Source>();
    list.Add(new Source());     
    list.AsQueryable().ProjectTo<Dest>().Dump();

示例https://dotnetfiddle.net/Ecovrp

最新更新