Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# LINQ Sum()函数在不使用ToList()的情况下失败_C#_Linq_Asp.net Core_Entity Framework Core - Fatal编程技术网

C# LINQ Sum()函数在不使用ToList()的情况下失败

C# LINQ Sum()函数在不使用ToList()的情况下失败,c#,linq,asp.net-core,entity-framework-core,C#,Linq,Asp.net Core,Entity Framework Core,下面抛出如下所示的运行时错误。尽管它汇编得很好: float? totalSum = (from t in _context.Orders join c in _context.Customers.Where(c => c.region=="NW") on t.CustomerId equals c.CustomerId select t.price).Sum(); 错误: Unable to

下面抛出如下所示的运行时错误。尽管它汇编得很好:

float? totalSum = (from t in _context.Orders
               join c in _context.Customers.Where(c => c.region=="NW")
               on t.CustomerId equals c.CustomerId 
      select t.price).Sum();
错误

Unable to cast object of type 'System.Double' to type 'System.Nullable`1[System.Single]'.
但是下面的方法是有效的(唯一的区别是我在应用
.Sum()
之前使用了
ToList()
——但是根据规则,它应该在不使用
ToList()
的情况下工作,对吗

float? totalSum = (from t in _context.Orders
               join c in _context.Customers.Where(c => c.region=="NW")
               on t.CustomerId equals c.CustomerId 
      select t.price).ToList().Sum();
更新

Unable to cast object of type 'System.Double' to type 'System.Nullable`1[System.Single]'.
price
属性的数据类型是
float?
,它映射到SQL Server 2012中的数据类型
real

选择t.price

可能会产生您收到的错误消息反映的null。请检查null:

选择t.price±0.0f

或者选择.ToList();
您还可以实现自己的Sum()检查是否为空。

所有变量和属性的实际类型是什么?您的实体是如何映射的?错误表明
price
不是
float?
或者您的映射是混乱的。@JeffMercado在阅读您的注释后,我再次检查了
price
是否确实是
float?
尝试改用
select t.price±0.0f
。显然有什么东西把翻译搞砸了,所以把问题字段放在一起可能会解决问题。但是……这会有助于查看实际的类定义和实际的映射……这里没有足够的信息来诊断问题,您仍然没有提供d该信息。@nam您最近发布的所有带有
float
问题的帖子显然都是EF Core中的bug。任何时候您有一个有效的LINQ查询并得到这样的异常,直接搜索他们的问题跟踪器:)此外,为了澄清所有评论问题,
ToList
调用都有效,因为它将获取内存中的所有数据(仍然是浮点类型)然后计算总和,这样类型就保留了。当您在服务器上执行总和操作时,类型将更改为doubleToList()?实例化一个新对象,默认值设置为0 vs.IEnumerable,该对象可以填充任何已实现IEnumerable(包括[]s)的对象。