简体   繁体   English

.Net(C#)中ISNULL()的等效方法是什么?

[英]What is the equivalent method to ISNULL() in .Net (C#)?

I have a stored procedure which used for my shopping cart system which returns the total amount and looks like this; 我有一个存储过程用于我的购物车系统,它返回总金额,看起来像这样;

ALTER PROCEDURE [dbo].[ShoppingCartGetTotalAmount]
(@CartID char(36))
AS
SELECT ISNULL(SUM(Product.Price * ShoppingCart.Quantity), 0)
FROM ShoppingCart INNER JOIN Product
ON ShoppingCart.ProductID = Product.ProductID
WHERE ShoppingCart.CartID = @CartID

However, Now I want to do the same thing in Entity Framework. 但是,现在我想在Entity Framework中做同样的事情。 Therefore, I need to know either of the following options; 因此,我需要知道以下任一选项;
1) How can I do the above task in Entity FrameWork ie 1)如何在Entity FrameWork中执行上述任务,即

SELECT ISNULL(SUM(Product.Price * ShoppingCart.Quantity), 0)
    FROM ShoppingCart INNER JOIN Product
    ON ShoppingCart.ProductID = Product.ProductID
    WHERE ShoppingCart.CartID = @CartID

2) Or What is the Equavilant to the SQL ISNULL() function in C#? 2)或者C#中SQL ISNULL()函数的等效性是什么?
3) Or How can I achieve this -> ISNULL(SUM(Product.Price * ShoppingCart.Quantity), 0) using any .Net method? 3)或者如何 使用任何.Net方法 实现这一点 - > ISNULL(SUM(Product.Price * ShoppingCart.Quantity), 0)

C# has the null coalesce operator - ?? C#有null coalesce运算符 - ?? .

The ?? ?? ?? operator is called the null-coalescing operator and is used to define a default value for nullable value types or reference types. operator被称为null-coalescing运算符,用于为可空值类型或引用类型定义默认值。 It returns the left-hand operand if the operand is not null; 如果操作数不为null,则返回左侧操作数; otherwise it returns the right operand. 否则返回正确的操作数。

EF understands this operator and translates it correctly. EF了解此运算符并正确翻译。

If you are trying to determine whether a value read from the database is null in the database, you need to compare the value to DBNull.Value. 如果要确定数据库中从数据库读取的值是否为空,则需要将该值与DBNull.Value进行比较。

For example, assume in the following code that oTotal holds the database result of Price * Quantity, the following is the equivalent of the SQL ISNULL operation: 例如,假设在以下代码中oTotal保存Price * Quantity的数据库结果,以下是SQL ISNULL操作的等效项:

decimal dTotal = (oTotal == DBNull.Value ? 0 : Convert.ToDecimal(oTotal));

In C# an extension method exists that is GetValueOrDefault for nullable types. 在C#中,存在一个扩展方法,即可以为可空类型的GetValueOrDefault So you can try this as well. 所以你也可以试试这个。 It will return the default value of if null consists. 它将返回if null包含的默认值。

decimal? oTotal = null;
decimal dTotal = oTotal.GetValueOrDefault(0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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