我将AutoMapper用于A和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; }
// ....
}在下列映射代码中
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上有以下警告
警告可能为空引用的CS8602解除引用。
如何不用#pragma warning disable CS8602消除警告
我尝试使用Null条件将o.MapFrom(s => s.X.Value)更改为o.MapFrom(s => s.X?.Value)。但是它在上得到了下面的错误。
错误CS8072表达式树lambda可能不包含空传播运算符
。
发布于 2019-12-26 16:28:32
由于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),如果要在空情况下赋值不同的值,可以结合三元运算符使用空合并运算符:
(s.X == null ? someDefaultValue : s.X.Value)
// e.g for string
(s.Text == null ? String.Empty : s.Text)https://stackoverflow.com/questions/59490921
复制相似问题