如何优化我的Linq查询?

时间:2012-03-22 07:44:09

标签: sql-server asp.net-mvc linq

我有两张表Room_masterRoom_Item

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查询以使其运行得更快?

1 个答案:

答案 0 :(得分: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)

应该为您提供没有分配项目的房间ID列表