2012-03-22 82 views
0

我有兩個表Room_masterRoom_Item如何優化我的Linq查詢?

Room_Master => roomid - pk, roomname 

Room_Item => roomiteid - pk, roomid - fk, itemid, quantity 

我想要的房間沒有分配任何項目的列表。

我寫了下面一個SQL查詢來獲取結果

select * from room where roomid in 
(select roomid from (select SUM(quantity) as qty, roomid from Room_Item group by roomid) 
as newtab where qty=0) order by roomid 

我相應的Linq查詢是如下

var roomitem1 = from ri in objEntities.Room_Item 
     group ri by ri.roomid into p 
       select new { roomid = p.Key, totalitem = p.Sum(row => row.quantity) }; 
var roomid = roomitem1.Where(x => x.totalitem > 0).Select(x => x.roomid); 

LINQ查詢工作很不錯,但問題是,它 需要很長的時間才能返回數據。我在Room_master表中有6000條記錄,在Room_item表中有大約70000條記錄,並且大約需要2分鐘才能將數據返回到我的視圖中...

如何優化我的Linq查詢以便運行更快?

+0

如果我看了你的代碼正確項房間ID的列表,然後LINQ查詢返回一個具有指定的至少一個項目,其中房間IDS因爲您的SQL查詢返回沒有分配項目的房間。 – ChrisWue 2012-03-22 07:52:22

+1

不需要SHOUT! – Phil 2012-03-22 07:59:14

回答

1

完全未經測試:

objEntities.Room_Item 
    .GroupBy(ri => ri.RoomId)     // group all items by room id 
    .Where(g => g.Sum(r => r.quantity) == 0) // where the total quantity of all items for that room id is 0 
    .Select(g => g.Key) 

應該給你沒有分配

+0

它工作得很好,謝謝@ChrisWue ... :) – 2012-03-22 08:09:28