简体   繁体   中英

How to get property from a nullable type?

I am trying to get the price total from an instance of a type that is in another table using virtual but the catch is that the instance can be null and whenever it is null it throws an exception. Is there any way to allow the type to be null and still get a return on the property?

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

Whenever product is null it throws an exception.

All you have to do is add the null propagation operator ? after the type.

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

This will mean that if Product is null, it will set the PriceTotal as null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM