Reputation: 23868
Following LINQ
query gives me the error shown below:
Error:
Unable to cast object of type 'System.Double' to type 'System.Nullable'1[System.Single]'.
LINQ query:
using (gEn myEntities = new gEn)
{
var load = (from items in myEntities.Orders
select items.PayO).Sum();
}
Model:
Public class Order
{
Public int OrdersId {get; set;}
Public float? PayO {get; set;}
}
NOTE:
real
and all its values are greater than zero (if that matters)select 2
the LINQ
query works fine and returns the sum of 2 repeated as many times as the number of rows in the table. For example if table has 4 rows, the LINQ
query will return 8
(i.e 2+2+2+2)Upvotes: 0
Views: 1628
Reputation: 5332
I am suspecting (cannot proof at this moment) that you have the problem with query materialisation!
When you execute this query:
var load = (from items in myEntities.Orders
select items.PayO).Sum();
It will be translated to this query:
SELECT SUM(PayO) FROM Order;
At this point, your query cannot handle null
values!
But when you do this (which I mentioned in comment above):
var pays = (from items in myEntities.Orders select items.PayO).ToList();
Your query will be executed and you will have in-memory list of float?
. At this point you can execute aggregation because Sum()
is able to handle null
values.
var load = pays.Sum();
load
is your sum.
Upvotes: 1
Reputation: 232
From what I see in the code. PayO is nullable, and the error clearly saying that it can't convert null to double. So you need to update your query to be like
using (gEn myEntities = new gEn)
{
var load = (from items in myEntities.Orders
where items.PayO != NULL
select items.PayO).Sum();
}
Upvotes: 0