null-coalescing operator ?? throws an error in LINQ

asp.net-core c# entity-framework-core linq

Question

Following LINQ query throws error shown below when using null-coalescing operator ??. It works fine if I remove ?? 0 part. But I do need to display 0 if t.cost is null. I'm trying to come up with LINQ equivalent of the IsNull(...) method of T-SQL as shown below.

T-SQL:

SELECT IsNuLL(cost,0) from Orders Where OrdId = 123

LINQ:

float? fCost = _context.Orders.Where(r => r.OrdId == 123).Select(t => t.cost ?? 0).SingleOrDefault();

Error on LINQ:

Unable to cast object of type `'System.Double' to type 'System.Single`

Note:

VS2015 recognizes the syntax ....Select(t => t.cost ?? 0).... and it compiles fine but error is thrown at run-time. Moreover; it also recognizes the syntax ....Select(t => (t.cost ?? 0)).... but throws the same error on it.

1
1
6/18/2017 3:50:35 AM

Accepted Answer

Your current query:

Single? cost = _context
    .Orders
    .Where( r => r.OrdId == 123 )
    .Select( t => t.cost ?? 0 )
    .SingleOrDefault();

Can be rewritten as:

Single? cost = _context.
    .Orders
    .SingleOrDefault( r => r.OrdId == 123 )
    ?.Cost;

cost will be null if there are no rows where r.OrderId == 123 or if r.Cost IS NULL (SQL NULL). Note my use of the ?. operator before .Cost.

1
6/18/2017 4:39:07 AM

Popular Answer

Try this.

float? fCost = _context.Orders.Where(r => r.OrdId == 123).Select(t => new { cost = (t.cost == DBNull.value ? 0 : t.cost) }).SingleOrDefault();


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow