2013-03-02 2 views
1

여러 테이블에 대해 LINQ NOT EXISTS를 수행하려고합니다.Linq NOT EXISTS 여러 테이블

Google 또는 SO의 모든 예제는 두 테이블을 처리합니다. 3 개로 작업 중이므로 제대로 참조하는 방법에 대해 LINQ의 초보자로 고심하고 있습니다.

는 우선 내가 가입에 대한 유형을 만드는 좋은 아니에요로에서 추악한 세 번 사용이 LINQ 쿼리

var nocertificates = (
    from x in rmdb.t_certificates 
    from ce in rmdb.t_user_certificates 
    from u in rmdb.t_users 
    where u.id == ce.uid && ce.value != x.id 
    select x).AsEnumerable().Select(x => new ViewModelCheckBox() 
     { 
     Value = x.id.ToString(), 
     Name = x.name, 
     Checked = false 
     }); 

을 시도했다. 는하지만 잘못된 결과를주고 내가이 가되지

그래서 나는 T-SQL이 SQL 쿼리가 작동합니다

에서 새 쿼리를 구축 EXISTS를 위해 가야했다 실현!

select distinct * from t_certificates tc 
where NOT EXISTS 
(
select distinct * from t_users tu, t_user_certificates tuc 
WHERE tu.email = '[email protected]' 
and tu.id = tuc.[uid] 
and tuc.value = tc.id 
) 

어떻게 LINQ에서 그렇게 할 것인가?

이 질문에 답해 드리겠습니다.

그러나!

우리가 대답 할 때 정말 궁금합니다. 존재하는 것과 존재하지 않는 것 모두를 가진 Ienumerable을 반환하는 하나의 LINQ 쿼리를 수행하는 것이 가능합니까?
이 존재 Checked 속성에 다른 값이 -> CHECKED = 진정한
는 NOT EXISTS -> = 체크

false이가 내 개체를 만드는 방법이다.

.Select(x => new ViewModelCheckBox() 
     { 
     Value = x.id.ToString(), 
     Name = x.name, 
     Checked = this should be different based on exists or not 
     }); 
+2

두 번째 질문입니다. 개념적으로 이것은 오른쪽 테이블의 nullableable 필드가 NULL 인 레코드 만 선택하는 WHERE 절이 포함 된 왼쪽 외부 조인입니다. –

답변

2

LINQ의 대답은 (안된를) 모양은 다음과 같습니다

var nocertificates = 
    from x in rmdb.t_certificates 
    join tuc in (
    from u in rmdb.t_users 
    join ce in rmdb.t_user_certificates on u.id == ce.uid 
    select ce.value 
) on tuc.value = tc.id into tuc 
    from y in tuc.DefaultIfEmpty() 
    where y == null 
    select x; 
+0

Hmmm somethings wrong, 테이블이 일관성이 없습니다 ... 나는 linq 및 SQL에 대한 다른 이름을 사용했습니다. (범위가 잘못되었습니다. – 8bitcat

2

이 내가 사용하는 결국 무엇인가!

var query = (from tc in rmdb.t_certificates 
      where !(
        from tu in rmdb.t_users 
        from tuc in rmdb.t_user_certificates 
        where tu.email == username 
        && tu.id == tuc.uid 
        && tuc.value == tc.id select tc).AsEnumerable().Any() 
        select new ViewModelCheckBox() 
           { Checked = false, 
            intconverter = tc.id, 
            Name = tc.name 
           });