nam
nam

Reputation: 23868

LINQ Sum method error

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:

  1. The PayO column of corresponding Orders table in SQL Server 2012 is of type real and all its values are greater than zero (if that matters)
  2. For testing purposes, in the above query if I replace select items.PayO by, say, 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

Answers (2)

kat1330
kat1330

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

Armin
Armin

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

Related Questions