我有一个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();
答案 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 })
});