2014-05-13 2 views
0

을이 사람은 작동하지 않습니다Linq에 where 절 - 비교 정수

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. 
+3

'itemEH' 란 무엇이고'itemEH.ID'의 유형은 무엇입니까? –

+1

가능한 복제가 [구체화 된 값이 null이므로 값 유형 'Int32'에 대한 캐스트가 실패했습니다.] (http://stackoverflow.com/questions/6864311/the-cast-to-value-type-int32-failed-because- the-materialized-value-is-null) –

+0

@JonSkeet이 대답을 편집했습니다 – Jude

답변

0

이 어떤 경우에는 성명서가

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

은 일치 항목이 없기 때문에 null 값을 반환합니다. 그러나 Sum() 메서드는 nullable이 아닌 정수를 반환하도록 설계되었으므로 반환 값으로의 변환이 실패합니다.

이는 전체 문이 SQL로 실행되고 합계가 없을 때 SQL이 아무것도 반환하지 않기 때문에 발생합니다. C# 코드가 인식하는 유일한 것은 반환 된 null 값입니다.

이 개체에 LINQ에 다른 : 합계 확장 방법이 컬렉션이 비어있을 때 0을 반환하도록 구현되어 있기 때문에

Enumerable.Empty<int>().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()