AutoMapping:取消引用可能为空的引用?空条件运算符不适用于 AutoMapping

ca9*_*3d9 2 c# automapper

我将 AutoMapper 用于 classA和B. 该项目是一个 .Net 核心项目,带有<Nullable>enabled</Nullable>.

public class A 
{
    public ClassX? X { get; set; } // ClassX is a custom class with the property of Value.
    //.... 
}

public class B 
{
    public string? X { get; set; } 
   // ....
}
Run Code Online (Sandbox Code Playgroud)

在下面的映射代码中

public void Mapping(Profile profile)
{
    // ....

    _ = profile?.CreateMap<A, B>()
        .ForMember(d => d.X, o => o.MapFrom(s => s.X.Value)); // warning on s.X
}
Run Code Online (Sandbox Code Playgroud)

它有以下警告s.X:

警告 CS8602 取消引用可能为空的引用。

如何在不使用的情况下摆脱警告#pragma warning disable CS8602?

我尝试更改o.MapFrom(s => s.X.Value)为o.MapFrom(s => s.X?.Value)使用 Null 条件。但它得到了下面的错误上s.X?.Value。

错误 CS8072 表达式树 lambda 可能不包含空传播运算符

Oli*_*bes 5

由于MapFrom接受 anExpression<>而不是 a Func<>,因此您不能使用 Null 条件运算符。这不是 AutoMapper 的限制,而是System.Linq.Expressions命名空间中的表达式树和 C# 编译器的限制。

但是,您可以使用三元运算符:

_ = profile?.CreateMap<A, B>()
    .ForMember(d => d.X, o => o.MapFrom(s => s.X == null ? null : s.X.Value));
Run Code Online (Sandbox Code Playgroud)

根据您的声明,该属性可以X为空。因此,如果它为空,您必须确保它不会被取消引用。

(根据@Attersson)如果要在空情况下分配不同的值,可以将空合并运算符与三元运算符结合使用:

_ = profile?.CreateMap<A, B>()
    .ForMember(d => d.X, o => o.MapFrom(s => s.X == null ? null : s.X.Value));
Run Code Online (Sandbox Code Playgroud)