Performance 如何使动态Linq查询更高效

Performance 如何使动态Linq查询更高效,performance,linq-to-entities,dynamic-linq,asp.net-mvc-controller,Performance,Linq To Entities,Dynamic Linq,Asp.net Mvc Controller,我已经编写了一个mvc控制器函数来处理动态查询,它工作得很好,但是对于一些更复杂的查询,它的响应时间实际上长达15秒。我使用ObjectQuery.ToTraceString获取sql并对我的数据库执行它,我得到了1-2秒的响应时间,虽然不是很好,但与我的服务器响应同一个查询所需的时间相差很大 这是我的密码: 公共类QueryController:控制器 { // //获取:/Query/ Entities1上下文=新的Entities1; 公共JsonResult查询 字符串选择, 字符串表=

我已经编写了一个mvc控制器函数来处理动态查询,它工作得很好,但是对于一些更复杂的查询,它的响应时间实际上长达15秒。我使用ObjectQuery.ToTraceString获取sql并对我的数据库执行它,我得到了1-2秒的响应时间,虽然不是很好,但与我的服务器响应同一个查询所需的时间相差很大

这是我的密码:

公共类QueryController:控制器 { // //获取:/Query/ Entities1上下文=新的Entities1; 公共JsonResult查询 字符串选择, 字符串表=产品, 字符串,其中=, 字符串groupBy= IQueryable数据表; 如果table==customerdatatable=Context.Customers; 如果table==productdatatable=Context.Products,则为else; 如果table==purchasedatatable=Context.Purchase,则为else; else dataTable=Context.Farms; 如果select==null,则返回null; 字符串where子句=where; 字符串selectClaus=select; 字符串groupByClaus=groupBy; IQueryable queryResults=数据表; 如果where!=queryResults=queryResults.where子句; 如果groupByClaus!=queryResults=queryResults.GroupBygroupByClaus,则它; queryResults=queryResults.selectClaus; JsonResult=新的JsonResult; 结果。数据=查询结果; result.JsonRequestBehavior=JsonRequestBehavior.AllowGet; 返回结果; } } 此代码应该处理如下请求:

 ?table=Purchase
 &select=new (Customer.First as Name, Product.Id as ProdId)
 &where=Category == 5
像上面这样的查询大约需要700毫秒,但如果我尝试更复杂的查询,它会慢到爬行15秒:

?table=Purchase
&select=new (
    count(true) as Total,
    Key.Product as Product,
    Key.CustomerRef as CustomerRef,
    count(Price > 475) as BigPurchases,
    count(PaidFor == false)  as UnPaid,
    count((Category != null) and (Comments == null) and Returns == null) as NoFeedback)
&groupBy=new (
    Product.ProductName as Product,
    CustomerRef as CustomerRef
    )
尤其是导航属性似乎是个问题,删除它会大大加快查询速度3秒:

?table=Purchase
&select=new (
    count(true) as Total,
    Key.Product as Product,
    Key.CustomerRef as CustomerRef,
    count(Price > 475) as BigPurchases,
    count(PaidFor == false)  as UnPaid,
    count((Category != null) and (Comments == null) and Returns == null) as NoFeedback)
&groupBy=new (
    ProductRef as Product,
    CustomerRef as CustomerRef
    )
时间似乎都被用来迭代IEnumerable,在我提供的代码中,我传递数据,让底层的MVC代码做它想要的任何转换,这大约需要提到的时间。然而,如果我自己迭代它,或者使用ToList函数,我得到的响应时间也会很慢

有人知道是什么导致了获取这些实体的长时间停顿吗

使现代化
我在数据库中添加了索引,这加快了速度,但在linq中执行查询的时间仍然是在sql中的20-30倍。

我尝试过使用不同的方法将IQueryable转换为可以返回的数组或列表,但我尝试的每种方法都需要相同的大量时间。我还列举了IQueryable,并对每次迭代进行计时,结果很有趣,1、2次迭代耗时1-2秒,第三次迭代耗时15秒,其余迭代耗时0毫秒。