Linq where子句 - 比较整数

时间:2014-05-13 17:29:25

标签: asp.net linq

这个不起作用:

var queryEH = from eh in entity.EmployeesHires where eh.ParentKey == item.PPYKey select eh;
foreach (var itemEH in queryEH)
{
   var query = (from el in entity.EmployeeLeaves where el.HireID == itemEH.ID select el.Duration).Sum();
}

而这一个确实:

var queryEH = from eh in entity.EmployeesHires where eh.ParentKey == item.PPYKey select eh;
foreach (var itemEH in queryEH)
{
   var query = (from el in entity.EmployeeLeaves where el.HireID == 125 select el.Duration).Sum();
}

第一个例外是:

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

1 个答案:

答案 0 :(得分:0)

这是因为在某些情况下声明

(from el in entity.EmployeeLeaves 
 where el.HireID == itemEH.ID select el.Duration).Sum()

返回null值,因为没有匹配项。但Sum()方法旨在返回(不可为空)整数,因此转换为返回值失败。

发生这种情况是因为整个语句在SQL中执行,并且当没有任何要求时,SQL不返回任何内容。 C#代码唯一知道的是返回的null值。

这在LINQ对象中是不同的:

Enumerable.Empty<int>().Sum()

请返回0,因为Sum扩展方法实现为在集合为空时返回0

当然你不应该通过切换到LINQ到对象来解决这个问题。你可以这样做:

(from el in entity.EmployeeLeaves 
 where el.HireID == itemEH.ID select el.Duration)
    .DefaultIfEmpty() // <= "inserts" a `0` when there is no result
    .Sum()
相关问题