简体   繁体   中英

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

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 ?

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).

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