Sql 实体框架orderby sum性能低下

Sql 实体框架orderby sum性能低下,sql,.net,asp.net-mvc,entity-framework-6,Sql,.net,Asp.net Mvc,Entity Framework 6,我有一个存储库表,并在此处添加任何产品事务,如下所示: productID qty: 103 2 103 -1 在我的产品视图中,我希望通过产品数量之和>0来显示产品订单 所以我写下: dbContext.tbl_Product.OrderByDescending(n => n.tbl_repository.Sum(x => x.Qty) > 0).ThenByDescending(m => m.ID); 但是,这项技术的性能太慢了,有没有其他方法可以加快速度 您可以

我有一个存储库表,并在此处添加任何产品事务,如下所示:

productID qty:
103 2
103 -1
在我的产品视图中,我希望通过产品数量之和>0来显示产品订单

所以我写下:

dbContext.tbl_Product.OrderByDescending(n => n.tbl_repository.Sum(x => x.Qty) > 0).ThenByDescending(m => m.ID);

但是,这项技术的性能太慢了,有没有其他方法可以加快速度

您可以尝试利用
GroupBy
方法

首先创建一个(可选)类来保存结果:

public class ProductGroup
{
    public string ProductID { get; set; } // or int, whatever your product id's type is
    public int QuantitySum { get; set; }
}
我不确定您的存储库是如何实现的,但请先尝试直接查询上下文,看看是否能获得更好的结果:

using (var db = new ApplicationContext())
{
    var products = db.Products
                     .GroupBy(product => product.ProductID)
                     .Where(productGroup => productGroup.Sum(p => p.Quantity) > 0)
                     .Select(productGroup => new ProductGroup { ProductID = productGroup.Key, QuantitySum = productGroup.Sum(product => product.Quantity) })
                     .OrderByDescending(product => product.ProductID)
                     .ToList();

    // 'products' should be a list of ProductGroup items holding the ID and Sum.
}

那张表里有多少条记录?这些表上有索引吗?从实体框架生成的SQL看起来像什么?@DarrenDavies存储库表中有50000条记录,我索引了productID和qty