[英]Optimise and speed up very slow Linq / SQL code
我有以下C#方法,可用於預加載庫存數據表。 盡管效果很好,但是現在表中有很多行,但是加載起來可能非常慢。
請有人可以推薦一種更好,更快的方法嗎? (理想情況是刪除“ foreach”代碼,因為這很慢!)。
public static DataTable GetProducts()
{
DataTable table = new DataTable();
using (DataClassesDataContext data = new DataClassesDataContext(cDbConnection.GetConnectionString()))
{
var query = (from p in data.Products
where p.Deleted == false
join s in data.ProductStocks on p.ProductID equals s.ProductID
group s by p into g
select new { g });
table.Columns.Add("Barcode", typeof(string));
table.Columns.Add("Stock Code", typeof(string));
table.Columns.Add("Description", typeof(string));
table.Columns.Add("Price", typeof(string));
table.Columns.Add("Tax", typeof(string));
table.Columns.Add("Stock", typeof(string));
table.Columns.Add("Service Item", typeof(bool));
table.Columns.Add("Deduct Stock", typeof(bool));
if (query != null)
{
foreach (var item in query)
{
try
{
decimal? Tax = 0;
if (item.g.Key.ProductTax != null)
{
Tax = Common.Utilities.IsValueValidDecimal(item.g.Key.ProductTax.TaxRate, 0); // Tax
}
else
{
Tax = 0;
}
bool DeductStock = !Convert.ToBoolean(item.g.Key.ServiceItem);
string[] row = new string[]
{
item.g.Key.EANCode.ToString(), // Barcode
item.g.Key.OurStockCode.ToString(), // Product Code
item.g.Key.Description.ToString(), // desc
GetGUIDisplayPrice(item.g.Key.RetailPrice, item.g.Key.RetailPriceExVAT), // cost
Tax.ToString(), // Tax
item.g.Sum(s => s.QtyOnHand).ToString(), // Stock
item.g.Key.ServiceItem.ToString(), // Service Item (non-stock)
DeductStock.ToString() // if not a service item, the its a stocked item so deduct!
};
table.Rows.Add(row);
}
catch (Exception ex)
{
}
}
}//ENDIF NULL
}//END USING
return table;
}
from p in data.Products
where p.Deleted == false
join s in data.ProductStocks on p.ProductID equals s.ProductID
group s by p into g
select new { g }
Products和ProductStocks表的架構是什么? 你有什么索引? 首先閱讀如何分析SQL Server性能 。
有些事情立即脫穎而出:
Deleted
位”字段可解決(性能)災難。 您可以將其添加到聚簇索引的最左鍵,其結果充其量是可疑的。 分區可以提供幫助,但作用不大。 沒有銀彈。 嘗試消除此要求。 刪除已刪除的行。 沒有太多優化空間。 停止獲取所有數據。
最后,此功能變成了一個存儲過程,該存儲過程返回了在服務器而非客戶端上創建的表。 這幾乎是即時的,巨大的性能改進!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.