[英]LINQ grouping by nullable child and parent
everyone! 大家! I've just faced a problem with timing out in my LINQ query. 我刚在LINQ查询中遇到超时问题。 I have 3 tables: Work, Projects and Subprojects. 我有3个表格:工作,项目和子项目。
Projects:
+--------+
| Id |<--+<--+
| Name | | |
+--------+ | |
SubProjects: | |
+--------+ | |
+->| Id | | |
| | Name | | |
| | ProjId |---+ |
| +--------+ |
| Work: |
| +------------+ |
| | Id | |
| | Type | |
| | ProjId |---+
+--| SubProjId | (nullable)
+------------+
I need to create a report based on Subprojects: 我需要基于子项目创建报告:
I've solved it by making two queries and then merging them, but when sometimes it times out. 我已经通过执行两个查询然后合并它们来解决它,但是有时会超时。 I was doing it with 我在做
result1.AddRange(result2);
because 因为
var temp = result1.Concat(result2);
is throwing an Exception: 抛出异常:
Internal .NET Framework Data Provider error 1004, 0, Unresolvable Var used in Command: VarType=Computed, Id=2090.
Can somebody help me with creating it in one query? 有人可以帮我在一个查询中创建它吗?
I'm not sure what your code looks like so this might not be perfect but you could try something like this: 我不确定您的代码是什么样子,因此这可能并不完美,但是您可以尝试执行以下操作:
var result = from work in works
group work by work.SubProjId ?? work.ProjId into groupedWorks
select groupedWorks.ToList();
or 要么
var result = works.GroupBy(work => work.SubProjId ?? work.ProjId).ToList();
试试这个查询
var itemlist =contex.Work.where(x=>x.SubProjId !=null).Groupby(x=>x.SubProjId).Concat(Contex.Work.where(x=>x.SubProjId ==null).Groupby(x=>x.ProjId)).ToList();
I'm guessing this is what you need: 我猜这是您需要的:
var groups = from work in ctx.Works // the work table
group work // we want to group whole work "rows"
// we are grouping by project id and subproject id
by new { ProjId = work.ProjId, SubProjId = work.SubProjId }
into g // and we are calling the grouping 'g'
select g; // select the group
// example of doing something with the groupings
foreach (var group in groups)
{
var key = group.Key; // gets a { ProjId, SubProjId } tuple
foreach (var work in group)
{
// each work is a row in the Work-table
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.