1

我在 SQL Azure 中有一个People大约 1000 行的表和一个大约 100 行的表。Dramas两者通过外键链接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();
4

1 回答 1

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 })
});
于 2013-09-29T22:24:17.667 回答