所以我几乎完成了弄清楚如何完成整个LINQ查询(我刚刚学习)我需要将另一个名为Project的表连接到这个linq查询并包含一个名为ProposedCompletionDate的字段。
现在它将在我调用FilterProjectAfterDate和FilterProjectBeforeDate的最小和最大日期之间过滤掉条目,并为TimeEntries中的每个唯一项目名称计算TimeWorked。
我的项目表包含了我想在此查询中包含的一些其他信息,如何将Project表加入到当前查询中? Project表的键是ProjectName和Phase。
以下是我的数据库表的数据类型 Project Table Data Types, TimeEntry Table Data Types
我当前的查询返回此信息: enter image description here
var result = context.TimeEntries.Where(Entry => Entry.Date >= FilterProjectAfterDate
&& Entry.Date <= FilterProjectBeforerDate
&& (FilterProjectName != null ? Entry.ProjectName.Contains(FilterProjectName) : true))
.GroupBy(m => new { m.ProjectName, m.Phase })
.Select(m => new {
Name = m.Key.ProjectName,
Phase = m.Key.Phase,
TimeWorked = m.Sum(o => o.TimeWorked)
});
谢谢大家!
答案 0 :(得分:0)
var result = ctx.TimeEntries
.Where(q => q.Date >= FilterProjectAfterDate)
.Where(q => q.Date <= FilterProjectBeforerDate)
.WhereIf(FilterProjectName != null, q => q.ProjectName.Contains(FilterProjectName))
.GroupBy(q => new { q.ProjectName, q.Phase })
.Join(ctx.Projects,
q => new { q.Key.ProjectName, q.Key.Phase },
w => new { w.ProjectName, w.Phase },
(q, w) => new { te = q, proj = w })
.Select(q => new
{
Name = q.te.Key.ProjectName,
Phase = q.te.Key.Phase,
TimeWorked = q.te.Sum(w => w.TimeWorked),
ProposedCompletionDate = q.proj.ProposedCompletionDate
});
WhereIf扩展方法:
public static IQueryable<TSource> WhereIf<TSource>(
this IQueryable<TSource> source, bool condition,
Expression<Func<TSource, bool>> predicate)
{
if (condition)
return source.Where(predicate);
else
return source;
}