2017-06-18 107 views
0

下面显示的运行时错误如下所示。虽然它编译罚款:LINQ Sum()函数在未使用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).Sum(); 

错误

Unable to cast object of type 'System.Double' to type 'System.Nullable`1[System.Single]'. 

但接下来的工作(唯一的区别是,我使用ToList()应用.Sum()前 - 但根据definition of Sum()它应该不工作正确?

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(); 

UPDATE

price属性的数据类型为float?映射到数据类型real在SQL Server 2012中

+0

什么是所有变量和属性的实际类型?你的实体如何映射?这个错误表明,“价格”不是“浮动”,或者你的映射混乱了。 –

+0

@JeffMercado在阅读您的评论后,我再次检查以确认'价格'确实是'浮动'? – nam

+0

尝试使用'select t.price? 0.0f'代替。显然有些东西搞砸了翻译,因此避开问题领域可能会解决这个问题。但是,仍然...这将有助于查看_actual_类定义和_actual_映射......没有足够的信息来诊断问题,但您仍然没有提供该信息。 –

回答

0

选择t.price

可能会产生您收到该错误消息,空反映。要么检查为空:

select t.price ?? 0.0f

或者去.ToList(); 你也可以实现你自己的Sum()来检查null。

+2

但是为什么它与ToList()一起工作? – MetaColon

+0

ToList()?实例化一个默认值设置为0的新对象,IEnumerable可以填充任何实现了IEnumerable包含[]的任何东西。 – map

相关问题