2011-11-21 54 views
0

我想將一個sql語句轉換爲linq,但也許我做錯了什麼,因爲我得到不同的結果。我正在LinqPad中嘗試我的linq聲明。試圖將sql查詢轉換爲linq,但是,我得到不同的結果

這裏是我的SQL statment:

SELECT set_id 
     FROM TestTable 
     WHERE rec_id In (25,32) 
     AND set_id NOT IN 
     (
     SELECT x.set_id FROM TestTable x 
     WHERE x.rec_id NOT IN(25,32) 
     ) 
     GROUP BY set_id 
     HAVING COUNT(set_id) = 2 

的Linq statment:

var recIdList = new List<int?>() { 25,32}; 

var query = from u in TestTables 
          where 
          (
           recIdList.Contains(u.Rec_id) && 
           !(from k in TestTables 
            where !recIdList.Contains(u.Rec_id) 
            select k.Set_id).Contains(u.Set_id) 
          ) 
          group u by u.Set_id into userGroup 
          where userGroup.Count() == recIdList.Count 
          select userGroup.Key; 
query.Dump(); 
TestTables.Dump(); 

通過LINQ的生成SQL查詢:

-- Region Parameters 
DECLARE @p0 Int = 25 
DECLARE @p1 Int = 32 
DECLARE @p2 Int = 25 
DECLARE @p3 Int = 32 
DECLARE @p4 Int = 2 
-- EndRegion 
SELECT [t2].[set_id] 
FROM (
    SELECT COUNT(*) AS [value], [t0].[set_id] 
    FROM [TestTable] AS [t0] 
    WHERE ([t0].[rec_id] IN (@p0, @p1)) AND (NOT (EXISTS(
     SELECT NULL AS [EMPTY] 
     FROM [TestTable] AS [t1] 
     WHERE ([t1].[set_id] = [t0].[set_id]) AND (NOT ([t0].[rec_id] IN (@p2, @p3))) 
     ))) 
    GROUP BY [t0].[set_id] 
    ) AS [t2] 
WHERE [t2].[value] = @p4 

TestTable的:

Create Table TestTable 
(
    set_id int, 
    rec_id int 
) 
Insert Into TestTable (set_id, rec_id) Values(10, 1) 
Insert Into TestTable (set_id, rec_id) Values(10, 25) 
Insert Into TestTable (set_id, rec_id) Values(10, 32) 
Insert Into TestTable (set_id, rec_id) Values(20, 61) 
Insert Into TestTable (set_id, rec_id) Values(20, 90) 
Insert Into TestTable (set_id, rec_id) Values(30, 77) 
Insert Into TestTable (set_id,rec_id) Values(11,25) 
Insert Into TestTable (set_id,rec_id) Values(11,32) 

GO 

對我的SQL查詢的結果:SET_ID 11
結果我的Linq查詢:SET_ID(10和11)

的想法是,我試圖讓SET_ID其中的·REC_ID正是(set_id 11:(25,32)),但是(set_id 10:(1,25,32))並不完全匹配。

我已經添加了兩個圖像,顯示結果使用LinqPad都設置:

SqlStatmentWithResultSet
LinqStatmentWihtResultSet

在此先感謝您的幫助......

+0

在您的LINQ語句中,在子查詢中,您有「!recIdList.Contains(u.Rec_id)」。如果這不是測試k.Rec_id? –

+0

非常感謝:$ ... 這樣做:):$ – Eyo

+0

我如何標記問題爲答案? 這是我在stackoverflow中的第二個問題:O – Eyo

回答

0

在你的LINQ聲明,在子查詢中,你有「!recIdList.Contains(u.Rec_id)」。如果這不是測試k.Rec_id?