Linq 查询在代码中引发超时,但在 LinqPad 上运行良好

问题描述

当我在 LinqPad 上运行 Linq 查询时,返回 5000 行只需要 4-5 秒,但是当我使用实体框架在我的代码中运行相同的查询时,它会引发超时。

可能的问题是什么?

提前致谢。

下面是查询

var resultSale =           
    from product in Products
    join productInfo in ProductInfoSummaries on product.ID equals productInfo.ProductID
    join productDetail in ProductDetails on new { Id = product.ID,storeId = product.CreatedInStore } equals new { Id = productDetail.ProductID,storeId = productDetail.StoreID }
    
    join productInventoryOtherStore in InventoryOtherStores on product.ID equals productInventoryOtherStore.ProductID
    into productInventories
    from productInventoryOtherStore in productInventories.DefaultIfEmpty()
    
    join saleLine in SaleLines on productDetail.ID equals saleLine.ArtikkelNr
    join sales in Sales on saleLine.OrderID equals sales.ID
    
    where saleLine.ArtikkelNr != null
    && saleLine.Datotid >= new DateTime(2018,01,01)
    && saleLine.Datotid <= new DateTime(2019,11,21)
    && sales.StoreID == 14
    && (sales.OrderType == 1 || sales.OrderType == 2 || sales.OrderType == 4 || sales.OrderType == 6)
    && productDetail.supplierProductNo != null
    && productDetail.Deleted == null
    && (productInfo.Inactive == null || productInfo.Inactive == false)
    && (product.CreatedInStore == 14 || product.CreatedInStore == 0 || product.CreatedInStore == null)
    
    group new { saleLine.AntallEnheter,sales.OrderType } by new { product.ID,productInventoryOtherStore.Amount } into g

    select new ProductSaleSummaryVM
    {
        ID = g.Key.ID,Inventory = (double)g.Key.Amount,TotalSold = g.Sum(x => x.OrderType !=4 ? x.AntallEnheter : 0) ?? 0,TotalWastage = g.Sum(x => x.OrderType ==4 ?  x.AntallEnheter : 0) ?? 0,TotalOrderedQty = 0
    };
    
var resultsupplierOrder = 
    from supplierOrderLine in supplierOrderLines
    join supplierOrder in supplierOrders on supplierOrderLine.supplierOrderID equals supplierOrder.ID
    where supplierOrderLine.Deleted == null
    && supplierOrder.Status != 1
    && supplierOrder.StoreID == 14
    group supplierOrderLine by supplierOrderLine.ProductID into g
    select new ProductOrderDetailsVM
    {
        ID = g.Key,TotalOrderedQty = (double)g.Sum(x => x.ConsumerQuantity - x.QuantiyReceived)
    };
    
var r =   
    (from resSale in resultSale
    join ressupplierOrder in resultsupplierOrder on resSale.ID equals ressupplierOrder.ID
    into ressupplierOrders
    from ressupplierOrder in ressupplierOrders.DefaultIfEmpty()
    orderby resSale.ID
    select new ProductSaleSummaryVM
    {
        ID = resSale.ID,Inventory = resSale.Inventory,TotalSold = resSale.TotalSold,TotalWastage = resSale.TotalWastage,TotalOrderedQty = ressupplierOrder.TotalOrderedQty ?? 0
    })
    .Where(x => x.Inventory +  x.TotalOrderedQty < x.TotalSold);
            
r.Dump();

解决方法

尝试在 linqpad 中使用实体框架,看看它是否给您任何线索。请参阅有关如何在 linqpad 中使用实体框架的链接

https://www.linqpad.net/EntityFramework.aspx