我正在使用EntityFramework 6并遇到一些重大速度问题 - 此查询需要两秒钟才能运行。为了加快查询速度,我花了LinqPad一整天的好时间,但我只能从4秒缩短到2秒。我试过分组,连接等,但生成的SQL对我来说看起来过于复杂。我猜测我只是采用错误的方法来编写LINQ。我需要帮助加快此EF LINQ查询
这里就是我试图做
- 找到所有
A
其中Valid
为null,并且AccountId
不是当前用户 - 确保的
B
的Collection
不包含任何B
哪里AccountId
是当前用户 - 将产生的
A
的B
数字排序在其下一个集合中丁订单 - 任何
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);
感谢
当测量查询执行时间,它是否包含EF的预热时间,或者是否在进行测量之前运行另一个查询?另外,这是您第一次运行特定查询吗?我相信EF 6会自动建立一个编译查询,这将使每个查询的第一次执行花费更长的时间。 – 2014-09-24 06:12:49
你在这些表中有多少行?你已经设置了一些索引?为什么是AccountId字符串? – 2014-09-24 07:29:45
表格之间的关系是什么?哪些列是其中的一部分? – user1429080 2014-09-24 08:59:33