2011-07-31 141 views
1

我一直在試圖解決這個整個一天.. :-(的LINQ to SQL返回錯誤結果

我使用C#與MSSQL,並通過LINQ

查詢我都存儲在一個集合在studWithTuiDisc變量,它包含下面的數據(在下面的鏈接示出)

image http://secompeusc.com/images/orig.png

當使用該變量作爲其他LINQ語句的結果是非常關,在此之前交我進行實驗以CHEC參考k如果真的不是我的錯誤,返回不正確的結果:

(1)我試圖迭代通過studWithTuiDisc,然後檢查關係只在select clause,因爲我確信這將返回所需的輸出(見下文)
代碼:

var xxx = (from a in studWithTuiDisc 
      select new 
      { 
      please = a.StudentId, 
      help = _conn.EEnrolledSubjects 
        .Where(m => m.StudentId == a.StudentId) 
        .Select(m => m.StudentId) 
        .FirstOrDefault() 
      }).Distinct(); 

輸出:
Control Experiment Output http://secompeusc.com/images/xxx.png

我們可以看到studWithTuiDisc值是唯一值包含在xxx

(2)現在我想,給了我很多頭痛的方法(見下文)
代碼:

var zzz = (from a in studWithTuiDisc 
      join b in _conn.EEnrolledSubjects on a.StudentId equals b.StudentId 
      select new { please = a.StudentId, help = b.StudentId }).Distinct(); 

var zzz = (from a in studWithTuiDisc 
      from b in _conn.EEnrolledSubjects 
      where a.StudentId == b.StudentId 
      select new { please = a.StudentId, help = b.StudentId }).Distinct(); 

輸出:
Experiment Output http://secompeusc.com/images/zzz.png

鑑於我們已經知道studWithTuiDisc中的值,並且因爲我們使用它作爲_conn.EEnrolledSubjects的篩選器,所以我們應該期待studWithTuiDisc中的結果,但在查看屏幕截圖時,LINQ沒有返回正確的結果。

我在做什麼錯?
有沒有人經歷過這樣的事情?
有誰知道爲什麼會發生這種情況?

+1

也許最好寫下來,格式化代碼和輸出,而不是發佈一些截圖? – abatishchev

+1

Omg,我發現查詢很難用這個奇怪的命名來閱讀。 「與Tui Disc搭檔」?!? – Phill

+0

@abatishchev這是直接從程序中取得的實際代碼 –

回答

1

使用DataContext.Log或SQL事件探查器檢查生成/發送到SQL Server的內容。我認爲你的問題會有所不同。

+0

對不起,我沒有解釋輸出: 這是正確的,它應該是新的{please = a.StudentId,help = b.StudentId}。請 - >代表studWithTuiDisc的StudentId。 help ---->代表StudentID來自_conn.EEnrolledSubjects 這裏的主題真的是爲什麼StudentId不包含在studWithTuiDisc中出現在結果中 –

+0

@LINQ Newbee:您可以使用代字符來突出顯示代碼' – abatishchev

+0

是的,它顯示了一個相當奇怪的生成的SQL,現在我可以從這裏獲取它。非常感謝。 –