很慢我正在這樣的代碼:Enumerable.Any()是大LINQ的數據集
var somethings = db.Somethings.Select(s => new SomethingViewModel
{
Id = s.Id,
Name = s.Name,
IsActive = s.IsActive
SubSomethings = s.SubSomethings.Select(ss => new SubSomethingViewModel
{
Id = ss.Id,
Name = ss.Name,
IsActive = ss.IsActive
}).Where(wss => wss.IsActive)
}).Where(ws => ws.IsActive && (ws.SubSomethings.Any())) //remove elements if no SubSomethings
.ToList();
正如你可以看到,這是一個一對多的關係。有一些SubSomethings的東西列表。如果我拿出& &(ws.SubSomethings.Any()),我會得到一個非常快速的返回列表。
但是,我只想在列表中包含至少有一個SubSomething的東西。我也試過以下,並得到了相同的可怕的效率:
var somethings = db.Somethings.Select(s => new SomethingViewModel
{
Id = s.Id,
Name = s.Name,
IsActive = s.IsActive
SubSomethings = s.SubSomethings.Select(ss => new SubSomethingViewModel
{
Id = ss.Id,
Name = ss.Name,
IsActive = ss.IsActive
}).Where(wss => wss.IsActive)
}).Where(ws => ws.IsActive)
.ToList(); //this finishes very quickly
var somethings2 = somethings.Where(s => s.SubSomethings.Any()).ToList(); //This is where the code bogged down
我怎樣才能重新寫我的查詢來獲取陷入泥淖代碼要快很多?有一件事要注意:這對一個或兩個記錄來說工作得很好。當我點擊> 8000條記錄時,至少需要四分鐘。
下面是我對SomethingId,其對應的外鍵的SubSomething表中創建的索引Something.Id
CREATE NONCLUSTERED INDEX [IX_SubSomething_SomethingId] ON [dbo].[SubSomething]
(
[SomethingId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
GO
這裏是SubSomething.SomethingId的創建外鍵:
ALTER TABLE [dbo].[SubSomething] WITH CHECK ADD CONSTRAINT [FK_SubSomething_Something_SomethingId] FOREIGN KEY([SomethingId])
REFERENCES [dbo].[Something] ([Id])
GO
ALTER TABLE [dbo].[SubSomething] CHECK CONSTRAINT [FK_SubSomething_Something_SomethingId]
GO
它應該給你相同的結果,但要嘗試不會傷害,如果使用'ws.SubSomethings.Count()> 0'代替'ws.SubSomethings.Any()'會發生什麼? – Gusman
@Gusman - 由於Count需要消耗整個數據,所以速度會更慢 –
@Gusman - 如果有的話,Count()方法會更慢,因爲它需要迭代所有項目以獲得計數是特定集合類型的一些捷徑,但不是全部)。 'Any()'只需要一個元素。 – DigiFriend