优化并加速非常慢的 Linq / SQL 代码
本文关键字:Linq SQL 代码 加速 非常 优化 | 更新日期: 2023-09-27 18:30:53
我有以下 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 }
"产品"和"产品库存"表的架构是什么?你有什么索引?首先阅读如何分析 SQL Server 性能。
有些事情立即突出:
- 您正在从客户端上的服务器获取所有数据。不要。后端的流程。
- 使用
Deleted
位字段会导致(性能)灾难。您可以将其添加到最左侧的聚集索引键,充其量只能获得可疑的结果。分区可以提供帮助,但不会太多。没有灵丹妙药。尝试消除此要求。删除已删除的行。
没有太多的优化空间。停止获取所有数据。
最后,此函数被转换为存储过程,存储过程返回在服务器上创建的表,而不是客户端。这几乎是即时和巨大的性能改进!