2014-09-24 57 views
3

我正在使用EntityFramework 6并遇到一些重大速度问题 - 此查询需要两秒钟才能运行。为了加快查询速度,我花了LinqPad一整天的好时间,但我只能从4秒缩短到2秒。我试过分组,连接等,但生成的SQL对我来说看起来过于复杂。我猜测我只是采用错误的方法来编写LINQ。我需要帮助加快此EF LINQ查询

这里就是我试图做

  1. 找到所有A其中Valid为null,并且AccountId不是当前用户
  2. 确保的BCollection不包含任何B哪里AccountId是当前用户
  3. 将产生的AB数字排序在其下一个集合中丁订单
  4. 任何A没有任何B应该在返回结果的末尾。

我必须模型看起来像这样:

public class A 
{ 
    public int Id { get; set; } 
    public bool? Valid { get; set; } 
    public string AccountId { get; set; } 
    public virtual ICollection<B> Collection { get; set; } 
} 

public class B 
{ 
    public int Id { get; set; } 
    public bool Valid { get; set; } 
    public string AccountId { get; set; } 
    public DateTime CreatedDate { get; set; } 
    public virtual A Property { get; set; } 
} 

该表为A有大约一百万行和B最终将有千万左右。现在B坐在50,000。

这是查询当前的样子。它给了我预期的结果,但我必须运行orderby多次,做其他不必要的步骤:

var filterA = this.context.A.Where(gt => gt.Valid == null && !gt.AccountId.Contains(account.Id)); 

var joinedQuery = from b in this.context.B.Where(gv => !gv.AccountId.Contains(account.Id)) 
          join a in filterA on gv.A equals a 
          where !a.Collection.Any(v => v.AccountId.Contains(account.Id)) 
          let count = gt.Collection.Count() 
          orderby count descending 
          select new { A = gt, Count = count }; 

IQueryable<GifTag> output = joinedQuery 
       .Where(t => t.A != null) 
       .Select(t => t.A) 
       .Distinct() 
       .Take(20) 
       .OrderBy(t => t.Collection.Count); 

感谢

+0

当测量查询执行时间,它是否包含EF的预热时间,或者是否在进行测量之前运行另一个查询?另外,这是您第一次运行特定查询吗?我相信EF 6会自动建立一个编译查询,这将使每个查询的第一次执行花费更长的时间。 – 2014-09-24 06:12:49

+1

你在这些表中有多少行?你已经设置了一些索引?为什么是AccountId字符串? – 2014-09-24 07:29:45

+0

表格之间的关系是什么?哪些列是其中的一部分? – user1429080 2014-09-24 08:59:33

回答

1

那么你总是可以尝试从joinQuery

删除这两条线其中!a.Collection.Any(v => v.AccountId.Contains(account.Id))

的OrderBy计数d escending

第一行已经在第一查询 和订单项目进行了筛选,做好做排序最终查询,所以没有点做两次

+0

我刚刚尝试删除一个“Contains”,它确实加快了查询速度。我需要确保它实际上返回正确的行。出于某种原因,我必须多次执行该命令,否则在分组后执行其他查询时会失序。 – 2014-09-24 13:45:20

+0

我想这个查询比我想象的要简单得多。将'Any'移出连接工作。 – 2014-09-24 13:57:01