我有以下LINQ to Entities查询,该查询具有许多子查询来获取一些汇总数据:
var systems = from s in db.Systems
orderby s.Name
select new SystemSummary
{
Id = s.Id,
Code = s.Code,
Name = s.Name,
LastException = (
from a in s.Applications
from e in a.Summaries
select e.CreationDate
).Max(),
TodaysExceptions = (
from a in s.Applications
from e in a.Summaries
where e.CreationDate >= today && e.CreationDate < tomorrow
select e
).Count(),
/* SNIP - 10-15 more subqueries */
};
我将查询缩短为仅包含2个子查询,但其中可能还有大约10-15个子查询。有没有一种方法可以重构查询以清理代码?我不是要提高性能。我想通过将子查询放入单独的方法中来清理代码,同时仍然确保它是对数据库的一次调用。 这可能吗?
最佳答案
我只是可以通过以下方式使其长度最小化(通过在原始查询中使用 let
关键字):
var subQuery = from a in s.Applications
from e in a.Summaries
select e;
您还可以进行一些重构,例如:
subQuery.Count(e=>e.CreationDate >= today && e.CreationDate < tomorrow);
subQuery.max(e=>e.CreationDate);
实际上,使用点表示法并将查询移至相关函数,而不是额外的
where
子句。并在查询中使用
subQuery
: from s in db.Systems
orderby s.Name
let subQuery = from a in s.Applications
from e in a.Summaries
select e
select new SystemSummary
{
Id = s.Id,
Code = s.Code,
Name = s.Name,
LastException = subQuery.max(e=>e.CreationDate),
TodaysExceptions = subQuery.Count(e=>e.CreationDate >= today
&& e.CreationDate < tomorrow),
/* SNIP - 10-15 more subqueries */
};
这仍然是对db的单次调用。
关于c# - 通过许多子查询将LINQ重构为SQL/实体查询,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9671246/