Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/facebook/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 用于获取记录计数的LINQ查询_C#_Linq - Fatal编程技术网

C# 用于获取记录计数的LINQ查询

C# 用于获取记录计数的LINQ查询,c#,linq,C#,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.Produc

我试图用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是的,我正在使用实体框架。谢谢你的建议