LINQ 左联接按顺序排列,末尾为空的右项

本文关键字:排列 顺序 LINQ | 更新日期: 2024-11-07 13:23:09

我对 LINQ 和实体框架的理解很少,而且我正在学习......

我正在尝试编写一个查询,该查询从名为 GroupView视图中获取信息,并在名为 GroupSequence 的表上进行左连接......然后,该信息将由<asp:Repeater>使用。

生成的集应包含 GroupView 中的所有项目,联接项位于开头(按GroupSequence表定义的顺序),未联接项位于末尾(按GroupViewId定义的顺序)。

即...

[GroupView]             |    [GroupSequence]
[Id]  [Name]   [Calc]   |    [Id]  [GroupId]  [UserId]  [Sequence]
1     Group 1  23       |    1     1          1         3
2     Group 2  34       |    2     2          1         2
3     Group 3  45       |    3     3          1         1
4     Group 4  56
5     Group 5  67

随着预期的结果...

[Id]  [Name]   [Calc]
3     Group 3  45
2     Group 2  34
1     Group 1  23
4     Group 4  56
5     Group 5  67

如果我执行以下操作,尽管使用了DefaultIfEmpty,我得到的只是链接到序列的 3 组。 但是页面显示,即使它只有 3 行......

from @group in context.GroupViews
join seq in context.GroupSequences on @group.Id equals seq.GroupId into groupSeq
from item in groupSeq.DefaultIfEmpty()
where item.UserId == 1
orderby item.Sequence
select new { Id = @group.Id, Name = @group.Name, Calc = @group.Calc };

如果我执行以下操作,中继器上的.DataBind会抱怨...

实体或复杂类型"DevModel.GroupSequence"不能在 LINQ to Entities 查询中构造

from @group in context.GroupViews
join seq in context.GroupSequences on @group.Id equals seq.GroupId into groupSeq
from item in groupSeq.DefaultIfEmpty(new GroupSequence { Id = @group.Id, UserId = 1, Sequence = @group.Id + 1000 })
where item.UserId == 1
orderby item.Sequence
select new { Id = @group.Id, Name = @group.Name, Calc = @group.Calc };

基于这个问题和公认的答案,我也尝试使用这样的 DTO......

class GroupViewSequenceDTO
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int? Calc { get; set; }
}
from @group in context.GroupViews
join seq in context.GroupSequences on @group.Id equals seq.GroupId into groupSeq
from item in groupSeq.DefaultIfEmpty(new GroupSequence { Id = @group.Id, UserId = 1, Sequence = @group.Id + 1000 })
where item.UserId == 1
orderby item.Sequence
select new GroupViewSequenceDTO { Id = @group.Id, Name = @group.Name, Calc = @group.Calc };

但是我仍然遇到与以前相同的错误(无法构建)

问题...

如何编写此查询,以便中继器显示所有 5 行,前 3 行按顺序排列,后 2 行相加? 我做错了什么?

LINQ 左联接按顺序排列,末尾为空的右项

您需要

将过滤器移动到左侧连接条件中,因为当item为空时,它将为假。

from @group in context.GroupViews
from seq in context.GroupSequences.Where(x => @group.Id == x.GroupId && x.UserId == 1).DefaultIfEmpty()
orderby seq.Sequence ?? int.MaxValue
select new GroupViewSequenceDTO 
{
   Id = @group.Id, 
   Name = @group.Name, 
   Calc = @group.Calc 
};