-2
我試圖從數據庫中檢索一些記錄以及LINQ的計數。LINQ查詢獲得記錄數
DataTable dtByRecipe = (from tbrp in context.tblRecipeParents
join tbrc in context.tblRecipeChilds on tbrp.RecipeParentID equals tbrc.RecipeParentID
join tbp in context.tblProducts on tbrc.ProductID equals tbp.ProductID
join tbps in context.tblProductSales.AsEnumerable()
on tbp.ProductID equals tbps.ProductID
join tbs in context.tblSales.AsEnumerable()
on tbps.ProductSalesID equals tbs.ProductSalesID select new
{
tbrp.Recipe,
tbp.ProductID,
tbps.ProductSalesID,
tbrp.Yield,
Product = tbp.ProductCode + " - " + tbp.ProductDescription,
ProductYield = tbrp.Yield,
TotalYield = "XXX",
Cost = "YYY"
}).AsEnumerable()
.Select(item => new {
item.Recipe,
Count = GetCount(item.ProductID, item.ProductSalesID, context),
item.Yield,
Product = item.Product,
ProductYield = item.ProductYield,
TotalYield = "XXX",
Cost = "YYY"
}).OrderBy(o => o.Recipe).ToDataTable();
private int GetCount (int ProductID, int ProductSalesID, MTBARKER_DBEntities context)
{
int query = (from tbps in context.tblProductSales
join tbp in context.tblProducts on tbps.ProductID equals tbp.ProductID
join tbs in context.tblSales
on tbps.ProductSalesID equals tbs.ProductSalesID
where tbp.ProductID == ProductID && tbps.ProductSalesID == ProductSalesID
select tbs).Count();
return query;
}
在上面的查詢中我得到預期的結果,但是因爲有10K左右的記錄在數據庫中消耗了大量的時間來產生結果。問題出在以下我用來計算的方法。
Count = GetCount(item.ProductID, item.ProductSalesID, context),
有沒有辦法,我可以防止這個問題的任何有效的方式?
你使用的是實體框架嗎?嘗試創建存儲過程並在EF中調用它。 – malkam
@malkam是的我正在使用實體框架。感謝您的建議 – chamara