这是一个关于速度的问题 - 有很多记录要访问。
问题基本信息
例如,我们将在数据库中拥有三个表。
关系:Order-ProductInOrder 是一对多(一个订单可以有多个产品) ProductInOrder-产品是一对一(订单中的一个产品由一个产品表示)
public class Order {
public bool Processed { get; set; }
// this determines whether the order has been processed
// - orders that have do not go through this again
public int OrderID { get; set; } //PK
public decimal TotalCost{ get; set; }
public List<ProductInOrder> ProductsInOrder;
// from one-to-many relationship with ProductInOrder
// the rest is irrelevant and will not be included here
}
//represents an product in an order - an order can have many products
public class ProductInOrder {
public int PIOD { get; set; } //PK
public int Quantity{ get; set; }
public int OrderID { get; set; }//FK
public Order TheOrder { get; set; }
// from one-to-many relationship with Order
public int ProductID { get; set; } //FK
public Product TheProduct{ get; set; }
//from one-to-one relationship with Product
}
//information about a product goes here
public class Product {
public int ProductID { get; set; } //PK
public decimal UnitPrice { get; set; } //the cost per item
// the rest is irrelevant to this question
}
假设我们收到一批订单,我们需要对其应用折扣并找到订单的总价。这可能适用于从 10,000 到超过 100,000 个订单的任何地方。其运作方式是,如果订单有 5 个或更多产品,每个产品的成本为 100 美元,我们将为总价提供 10% 的折扣。
我试过的
我尝试了以下方法:
//this part gets the product in order with over 5 items
List<Order> discountedOrders = orderRepo
.Where(p => p.Processed == false)
.ToList();
List<ProductInOrder> discountedProducts = discountedOrders
.SelectMany(p => p.ProductsInOrder)
.Where(q => q.Quantity >=5 )
.ToList();
discountedProducts = discountedProducts
.Where(p => p.Product.UnitPrice >= 100.00)
.ToList();
discountOrders = discountedOrders
.Where(p => discountProducts.Any(q => q.OrderID == p.OrderID))
.ToList();
这非常慢并且需要永远运行,当我在它上面运行集成测试时,测试似乎超时。我想知道是否有更快的方法来做到这一点。