LINQ to Entities选择需要很长时间

时间:2013-09-29 12:02:18

标签: c# performance linq entity-framework linq-to-entities

我有一个People表,大约有1000行,Dramas表在SQL Azure中有大约100行。这两个链接与外键Drama.PersonId链接,以便每个人可以有0或更多的戏剧。

以下代码的行为与预期一致,大约有50人及其相关的近期剧集。但是,运行需要5秒以上(使用Stopwatch测量)。必须有一些效率低下的东西?

var people = ctx.People
  .Where(p => p.Dramas.Any(d => d.DateHappened >= startDate))
  .Select(p => new
    {
      p.FirstName,
      p.LastName,
      Dramas = p.Dramas.Where(d => d.DateHappened >= startDate).Select(d => new { d.Id, d.DramaType })
    }).AsEnumerable();

1 个答案:

答案 0 :(得分:0)

通过首先获取所有最近的剧集,然后发送单独的查询来获取人物,我的速度更快了。它使用PredicateBuilder

var dramasByPerson = ctx.Dramas.Where(d => d.DateHappened >= startDate)
  .Select(d => new { d.PersonId, d.Id, d.DramaType })
  .ToLookup(d => d.PersonId);

var predicate = dramasByPerson.Select(o => o.Key)
  .Aggregate(
    PredicateBuilder.False<Person>(),
    (current, personId) => current.Or(o => o.PersonId == personId)
  );

var dictPeople = ctx.People.Where(predicate)
  .Select(o => new { o.PersonId, o.LastName, o.FirstName })
  .ToDictionary(o => o.PersonId);

var people = dramasByPerson.Select(o => new {
  LastName = people[o.Key].LastName,
  FirstName = people[o.Key].FirstName,
  Dramas = o.Select(d => new { d.Id, d.DramaType })
});