如何从可为空的类型获取属性?

时间:2019-08-09 18:41:42

标签: c# entity-framework linq

我正在尝试使用virtual从另一个表中的某个类型的实例获取价格总和,但要注意的是该实例可以为null,并且无论何时为null都会引发异常。有什么方法可以让类型为null并仍然获得属性的回报?

// Trying to get product price from products table, throws exception when Product is null
            {order.Product.PriceTotal}

每当product为null时,都会引发异常。

1 个答案:

答案 0 :(得分:0)

您要做的就是在类型之后添加空传播运算符?

// Trying to get product price from products table, throws exception when Product is null
            {order.Product?.PriceTotal}

这意味着如果Product为空,则会将PriceTotal设置为空