想起我之前在此列表中加入了一個字段,用於方便提示管理員公司的產品列表是否有修改之類的狀態字段,於是可以斷定是加了此字段的原因。
首先,先看看我之前是如何寫這個提示狀態字段的,實體中加入ContentStatus,然後直接在Linq語句中Select 實體對象中加入ContentStatus=Product_Maintain.Count(C => C.CompanyID == company.ID && C.IsDeleted == 0 && (C.AuditStatus == 0 || C.AuditStatus == 4))>0?"產品有更新":""。這時我想應該是加入三元運算,linq在轉Sql時,產生過多的,Case,when ,then語句,三元運算增加了判斷會影響查詢性能,於是我去掉後,再運行查看頁面,仍然很慢,感覺不出快了多少。
這時,我想起了LinqPad,看看到底轉換生成了怎樣的Sql語句。運用Count(條件)生成Sql代碼如下:
復制代碼 代碼如下:
SELECT COUNT(*) AS [value]
FROM (
SELECT
(CASE
WHEN ([t1].[CompanyID] = ([t0].[ID])) AND ([t1].[IsDeleted] = @p0) AND (([t1].[AuditStatus] = @p1) OR ([t1].[AuditStatus] = @p2)) THEN 1
WHEN NOT (([t1].[CompanyID] = ([t0].[ID])) AND ([t1].[IsDeleted] = @p0) AND (([t1].[AuditStatus] = @p1) OR ([t1].[AuditStatus] = @p2))) THEN 0
ELSE NULL
END) AS [value]
FROM [Company_Product_Maintain] AS [t1]
) AS [t2]
WHERE [t2].[value] = 1
這時我發現一個很簡單的Count的Sql 語句,linq轉換後變得如此復雜,我直接在sql server中運行此代碼,發現查詢還是很慢,於是我直接把ContentStatus=Product_Maintain.Where(C => C.CompanyID == company.ID && C.IsDeleted == 0 && (C.AuditStatus == 0 || C.AuditStatus == 4)).Count()生成Sql語句為:
代碼
復制代碼 代碼如下:
SELECT COUNT(*) AS [value]
FROM [GasSNS_Company_Equipment_Maintain] AS [t1]
WHERE ([t1].[CompanyID] = ([t0].[ID])) AND ([t1].[IsDeleted] = @p0) AND (([t1].[AuditStatus] = @p1) OR ([t1].[AuditStatus] = @p2))
發現運行速度那是快了一個數量級啊!
後台列表查詢結果速度大大提升有圖為證(聲明:以下圖都為項目中截圖,不是簡單的單表查詢,還連了用戶表,詳細表等數量也都挺大的):
圖1為Count結果,用了35秒,哇塞!
圖2為Where(條件).Count()結果,同樣的數據只用了4秒鐘,差了10倍!
然後為了取值方面我還是加入三元運算,ContentStatus=Product_Maintain.Where(C => C.CompanyID == company.ID && C.IsDeleted == 0 && (C.AuditStatus == 0 || C.AuditStatus == 4)).Count()>0?"產品有更新":""。結果如下:
真的是Count()與 Where()區別,不可能這麼大差距吧?於是我單寫 Product_Maintain.Where(C => C.IsDeleted == 0 && (C.AuditStatus == 0 || C.AuditStatus == 4)).Count() 與 Product_Maintain.Count(C => C.IsDeleted == 0 && (C.AuditStatus == 0 || C.AuditStatus == 4)) 發現速度差不多,生成的代碼是一樣的。