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.
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
.
Try this.
float? fCost = _context.Orders.Where(r => r.OrdId == 123).Select(t => new { cost = (t.cost == DBNull.value ? 0 : t.cost) }).SingleOrDefault();