3

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. Therefore, I need to know either of the following options;
1) How can I do the above task in Entity FrameWork i-e

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#?
3) Or How can I achieve this -> ISNULL(SUM(Product.Price * ShoppingCart.Quantity), 0) using any .Net method?

Idrees Khan
  • 7,702
  • 18
  • 63
  • 111
  • Have you considered `ExecuteFunction` instead of refactoring the wheel? – podiluska Sep 02 '12 at 18:24
  • Entity Framework has ExecuteFunction which allows you to call stored procedures. – podiluska Sep 02 '12 at 18:27
  • I get it, but I want to use the entity framework query (because I have already work with ado.net) and now I want to learn entity framework. Therfore, I am not going to use stored proce for now. – Idrees Khan Sep 02 '12 at 18:29
  • Possible duplicate of [C# equivalent of the IsNull() function in SQL Server](http://stackoverflow.com/questions/169217/c-sharp-equivalent-of-the-isnull-function-in-sql-server) – Aaroninus Jan 07 '16 at 15:45

3 Answers3

7

C# has the null coalesce operator - ??.

The ?? operator is called the null-coalescing operator and is used to define a default value for nullable value types or reference types. It returns the left-hand operand if the operand is not null; otherwise it returns the right operand.

EF understands this operator and translates it correctly.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
2

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.

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:

decimal dTotal = (oTotal == DBNull.Value ? 0 : Convert.ToDecimal(oTotal));
competent_tech
  • 44,465
  • 11
  • 90
  • 113
0

In C# an extension method exists that is GetValueOrDefault for nullable types. So you can try this as well. It will return the default value of if null consists.

decimal? oTotal = null;
decimal dTotal = oTotal.GetValueOrDefault(0);
Kundan Singh Chouhan
  • 13,952
  • 4
  • 27
  • 32