我正在处理以下的Entity Framework查询。我知道这里有很多内容,但希望足够清晰以便于别人可以发现问题。
var lineItems = from li in Repository.Query<CostingLineItem>()
let cid = (li.ParentCostingPackage != null) ?
li.ParentCostingPackage.ParentCostingEvent.ProposalSection.Proposal.Costing.Id :
li.ParentCostingEvent.ProposalSection.Proposal.Costing.Id
where cid == costingId &&
li.OriginalProductId.HasValue &&
(li.Quantity.HasValue && li.Quantity.Value > 0) && // li.QuantityUnitMultiplier
Classifications.Contains(li.OriginalProduct.ClassificationEnumIndex)
let selectedChoiceId = li.OriginalPackageOptionId.HasValue ?
(from c in li.OriginalPackageOption.CostingLineItems
orderby (c.IsIncluded ?? false) ? -2 : (c.IsDefaultItem ?? false) ? -1 : c.Id
select (int)c.OriginalPackageOptionChoiceId).FirstOrDefault() :
0
where selectedChoiceId == 0 || (li.OriginalPackageOptionChoiceId.HasValue && li.OriginalPackageOptionId.Value == selectedChoiceId)
let hasProviderAvailable = li.OriginalProductItem.ProductItemVendors.Any(
piv => piv.ProductPricings.Any(pp => pp.ProductItemVendor.CompanyId != null || pp.ProductItemVendor.HotelId != null))
select new
{
LineItem = li,
ProductItem = li.OriginalProductItem,
Product = li.OriginalProduct,
Vendors = li.CostingLineItemVendors,
HasProviderAvailable = hasProviderAvailable
};
原始查询会生成以下运行时错误:
等待操作超时
如果我将声明 selectedChoiceId
的部分更改为以下内容,则可以消除该错误:
let selectedChoiceId = 0
有人能看出那段代码为什么会一直导致超时错误吗?
(注意:这段代码是一个运行多年的大型应用程序的一部分。所以我真的不认为这与连接字符串或类似的东西有任何关系。如果我进行上述更改,它就能稳定运行。)
selectedChoiceId
的声明会导致 EF 向 SQL Server 发送一个更复杂的子查询,因此自然而然地删除它会执行得更快(因此没有超时)。我会附加分析器,捕获生成的 SQL,并调查其预估执行计划,以查看它命中了哪些索引以及如何命中。 - Nick Patsarisvar choice = (from c in li.OriginalPackageOption.CostingLineItems orderby (c.IsIncluded ?? false) ? -2 : (c.IsDefaultItem ?? false) ? -1 : c.Id select (int)c.OriginalPackageOptionChoiceId).FirstOrDefault() : 0
然后使用let selectedChoiceId = choice
,我认为子查询可能出现问题。 - Nilesh