Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert ToDecimal from Decimal? returns sometimes returns null instead of 0

Tags:

c#

linq

In my test below, result returns 0

 decimal? t = null;
 decimal result = Convert.ToDecimal(t);

But in my Linq query

 var query = from c in dc.DataContext.vw_WebOrders
    select new CisStoreData()
    {
       Discount = Convert.ToDecimal(c.Discount)
    };

Convert.ToDecimal() returns null and my query throws an exception when it is converted to a List because Discount is not nullable. Why is this happening? Shouldn't a null decimal always return 0?

like image 699
tony95 Avatar asked Dec 13 '25 21:12

tony95


1 Answers

The LINQ query is never actually executed as C# code. It is compiled into an expression which is passed to a query provider which is able to inspect what you wrote and create a semantically equivalent SQL query to the best of its ability. Of course, while it does its best to have exactly the same semantics, it will not always succeed, either because the query provider doesn't properly translate those semantics, or sometimes because the database that the query is being written for doesn't have operations with the desired semantics (or perhaps because it intentionally creates slightly different semantics).

like image 50
Servy Avatar answered Dec 16 '25 12:12

Servy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!