var xs = (from x in dbContext.db_API_Operationallog where x.id<1 select 1 ).Count(); 結果: SELECT [GroupBy1].[A1] AS [C1] FROM ( SELECT COUNT(1) AS [A1] FROM [dbo].[db_API_Operationallog] AS [Extent1] WHERE [Extent1].[id] < 1 ) AS [GroupBy1]
context.db_API_Operationallog.FirstOrDefault(p => p.Id == postId).Hits; 或者: context.db_API_Operationallog.Find(postId).Hits;
會把整個post表數據都查出而後再內存裏面找了hits這個列sql
優化:post
context.db_API_Operationallog.Where(p => p.Id == postId).Select(p => p.Hits).FirstOrDefault();
有時候一個不當心在查詢的sql build 裏面加了個tolist(), toArray()等,這種真正的執行了查詢,這樣在開發環境每每表的數據比較少,程序運行比較快,可是一到線上環境數據量比較大的狀況下就會出現內存爆滿的問題,這個問題相對來講比較隱蔽,因此開發的時候必定要當心。優化
public IEnumerable<db_API_Operationallog> GetAllPost() { return context.Post; } int id = 2000; var log = GetAllPost().Where(s => s.id <id).ToList();
Sql Server Profiler 抓到的信息ui
SELECT [Extent1].[id] AS [id], [Extent1].[uid] AS [uid], [Extent1].[types] AS [types], [Extent1].[events] AS [events], [Extent1].[more] AS [more], [Extent1].[money] AS [money], [Extent1].[lastmoney] AS [lastmoney], [Extent1].[nowmoney] AS [nowmoney], [Extent1].[bak] AS [bak], [Extent1].[times] AS [times] FROM [dbo].[db_API_Operationallog] AS [Extent1]
exec sp_executesql N'SELECT [Extent1].[id] AS [id], [Extent1].[uid] AS [uid], [Extent1].[types] AS [types], [Extent1].[events] AS [events], [Extent1].[more] AS [more], [Extent1].[money] AS [money], [Extent1].[lastmoney] AS [lastmoney], [Extent1].[nowmoney] AS [nowmoney], [Extent1].[bak] AS [bak], [Extent1].[times] AS [times] FROM [dbo].[db_API_Operationallog] AS [Extent1] WHERE [Extent1].[id] < @p__linq__0',N'@p__linq__0 int',@p__linq__0=2000
這個坑是比較一樣也是比較隱蔽的注意下code
dbContext.db_API_Operationallog.Where(s => s.id < id).AsNoTracking().ToList();
平時寫EF的時候必定要把腳步停下了 多使用 Sql Server Profiler 琢磨下本身的代碼內存