【问题标题】:entity framework orderby sum slow performance实体框架 orderby sum 性能慢
【发布时间】:2016-02-27 00:07:46
【问题描述】:

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

productID qty:
103 2
103 -1

在我的产品视图中,我想按产品数量的总和显示产品订单 > 0

所以我写了这个:

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

但是这个性能太慢了,有没有其他方法可以让它更快?

【问题讨论】:

  • 该表中有多少条记录?这些表上是否有索引?从 Entity Framework 生成的 SQL 是什么样的?
  • @DarrenDavies 存储库表中有 50000 条记录,我索引了 productID 和 qty

标签: sql .net asp.net-mvc entity-framework-6


【解决方案1】:

您可以尝试利用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.
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-28
    • 2010-12-23
    相关资源
    最近更新 更多