2016-04-25 124 views
0

試圖轉換一個查詢,其中有兩個級別的where子句linq和獲取一些錯誤。有人可以幫助我嗎?在子句中使用linq

原始查詢:

select id 
from student 
where suId 
in (select suId 
    from subjects 
    where cid 
    in (select id 
     from chapters 
     where chapter='C203')) 

LINQ查詢:

var query = (from s in dc.students 
     let subs = (from su in dc.subjects 
         where su.cid == Convert.ToInt32(from c in dc.Chapters 
                  where c.chapter == 'Ç203' 
                  select c.id) //Single chapter id will be returned 
         select su.suid) 
     where subs.Contains(s.sid) 
     select s.id).ToArray(); 

我得到以下2個錯誤,而編譯應用程序

  1. 'System.Linq.IQueryable' 不包含一個定義爲'Contains'和最好的擴展方法重載'System.Linq.ParallelEnumerable.Contains(System.Linq.ParallelQuery,TSource)'有一些無效參數
  2. 實例參數:無法從「System.Linq.IQueryable」轉換爲「System.Linq.ParallelQuery」

回答

0

由於Linq被延遲加載一切你並不需要所有東西都塞進單一的陳述;你可以這樣做:

var chapterIds = dc.Chapters 
    .Where(c => c.Chapter == "C023") 
    .Select(c => c.Id); 
var subjectIds = dc.Subjects 
    .Where(s => chapterIds.Contains(s.Cid)) 
    .Select(s => s.Suid); 
var students = dc.Students 
    .Where(s => subjectIds.Contains(s.Suid)) 
    .Select(s => s.Sid) 
    .ToArray(); 

這樣你就可以通過查看返回的內容來調試每個子查詢。

然而,看着你原來的選擇,你可以重寫整個事情的Join和擺脫竊聽問題:

var students = dc.Chapters.Where(c => c.Chapter == "C023") 
    .Join(dc.Subjects, 
     c => c.Id, 
     s => s.Cid, 
     (chapter, subject) => subject) 
    .Join(dc.Students, 
     subj => subj.Suid, 
     student => student.Suid, 
     (subj, st) => st.Sid) 
    .ToArray(); 
+0

似乎加入被更簡單的解決方案。謝謝 – user3625533