Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq error generic parameter or the query must use a nullable type

Tags:

null

linq

I got this error when i use sum function in LINQ:

The cast to value type 'Decimal' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.

GroupProduct.Where(a => a.Product.ProductID==1).Sum(Content => Content.Amount==null?0:Content.Amount),
like image 948
malik Avatar asked Jan 16 '10 09:01

malik


2 Answers

This is what I usually use. This will cover the possibility of Amount being null and also cover the possibility of an empty set.

GroupProduct.Where(a => a.Product.ProductID == 1)
    .Select(c => c.Amount ?? 0) // select only the amount field
    .DefaultIfEmpty()  // if selection result is empty, return the default value
    .Sum(c => c)

DefaultIfEmpty() returns the default value associated with Amount's type, which is int, in which case the default value is 0.

like image 165
mendel Avatar answered Oct 02 '22 03:10

mendel


Did you try the following:

GroupProduct.Where(a => a.Product.ProductID==1).Sum(Content => (decimal?)Content.Amount)

The code from my application looks like:

var data = query.AsEnumerable().Select(row => TaskInfo.FetchTaskInfo(row,
      ctx.ObjectContext.Hours.Where(hour => hour.TaskId == row.TaskId).Sum(hour => (decimal?)hour.Duration),
      ctx.ObjectContext.Notes.Count(note => note.SourceType == (int)SourceType.Task && note.SourceId == row.TaskId)));
like image 43
mattruma Avatar answered Oct 02 '22 02:10

mattruma