문제

이상한 LINQ 하위 쿼리 문제가 있습니다.

다음 데이터 구조가 주어지면 :

Parents            Children
-------            --------
Id                 Id
                   ParentId
                   Location
                   HasFoo

(분명히 이것은 실제 구조는 아니지만이 예에 대해 충분히 가깝습니다)

이 쿼리를 실행하고 원하는 결과를 얻을 수 있습니다.

bool b = (from p in Parents
          from c in Children
          where p.Id == 1 && c.ParentId == p.Id && c.Location == "Home"
          select c.HasFoo).SingleOrDefault();

따라서 ID 1의 부모의 위치 "홈"이있는 아이가 있다면, 그 아이의 "Hasfoo"값을 얻을 것입니다. 그렇지 않으면 Bool의 "기본값"값 인 False를 얻을 것입니다.

그러나 쿼리를 쓰려고 시도하면 다음과 같은 부모 객체 목록이 있습니다.

var parentList = from p in Parents
                 select new ParentObject
                 {
                   ParentId = p.ParentId,
                   HasHomeChildren = p.Children.Count(c => c.Location == "Home") > 0,
                   HasHomeChildrenWithFoo = (from c in p.Children where c.Location == "Home" select c.HasFoo).SingleOrDefault()
                 }

목록을 반복 할 때 다음과 같은 오류가 발생합니다.

The null value cannot be assigned to a member with type System.Boolean which is a non-nullable value type.

그러나이 "NULL"값이 어디에서 오는지 알 수 없습니다.

도움이 되었습니까?

해결책

컴파일러가 hashomechildrenwithfoo를 bool로 유추하고 있는지, 실제로 무효가 가능한 부를 캐스팅하는지 궁금합니다 (따라서 Singleordefault 호출을 엉망으로 만들었습니다). 어쨌든, 나는 당신이 최종 선택에서 무효 유형으로 캐스트로 그것을 고칠 수있을 것입니다. 그러면 Null이면 거짓으로 수동으로 거짓으로 기본값을받을 수 있습니다. 아마도 오류가 사라질 것입니다.

var parentList = from p in Parents
                 select new ParentObject
                 {
                   ParentId = p.ParentId,
                   HasHomeChildren = p.Children.Any(c => c.Location == "Home"),
                   HasHomeChildrenWithFoo = (from c in p.Children where c.Location == "Home" select (bool?)c.HasFoo) ?? false)
                 }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top