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

AutoMapping: Dereference of a possibly null reference? Null-conditional operator doesn't work with AutoMapping

我正在为 class AB 使用 AutoMapper。该项目是 <Nullable>enabled</Nullable>.

的 .Net 核心项目
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; } 
   // ....
}

在下面的映射代码中

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

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

它在 s.X 上有以下警告:

Warning CS8602 Dereference of a possibly null reference.

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

我尝试使用 Null 条件将 o.MapFrom(s => s.X.Value) 更改为 o.MapFrom(s => s.X?.Value)。但是它在 s.X?.Value.

上得到了以下 error

Error CS8072 An expression tree lambda may not contain a null propagating operator

由于 MapFrom 接受 Expression<> 而不是 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));

根据您的声明,属性 X 可以为空。所以一定要保证为null不被解引用

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

(s.X == null ? someDefaultValue : s.X.Value)

// e.g for string
(s.Text == null ? String.Empty : s.Text)