【问题标题】:How to sort a child list in Linq2DB?如何对 Linq2DB 中的子列表进行排序?
【发布时间】:2021-12-16 14:48:28
【问题描述】:

我有一个表,其中每一行都拥有另一个表中的一组行,使用 LinqToDB.Mapping 类。

[Table(Name = "SECTORS")]
public partial class Sector
{
    [Column(Name="ID"), NotNull, PrimaryKey] 
    public int Id { get; set; }

    [Column(Name = "NAME"), NotNull] 
    public string Name { get; set; }

    [Association(ThisKey = nameof(Id), OtherKey = nameof(SubSector.SectorId))]
    public List<SubSector> Subsectors { get; set; }
}

[Table(Name = "SUBSECTORS")]
public partial class SubSector : Sector
{
    [Column(Name = "SECTORID"), NotNull]
    public int SectorId { get; set; }
}

我已经研究了如何在加载父对象列表时使用关联标头自动加载所有子对象。

var query = from s in Sectors.LoadWith(s => s.Subsectors)
                        orderby s.Name
                        select s;
            

如何为Subsectors 列表设置排序顺序?

我可以稍后对其进行排序,但最好由数据库完成排序。

似乎没有 Association 属性的属性,并且添加到 orderby 行将对父对象进行排序(如果它甚至可以工作的话)。

【问题讨论】:

  • 你试过Sectors.LoadWith(s =&gt; s.Subsectors.OrderBy(x =&gt; x.SectorId ))吗?
  • @SvyatoslavDanyliv - 太棒了,效果很好(而且速度也很快!)。你想提交它作为答案,还是我应该为你做?

标签: c# linq2db


【解决方案1】:

LoadWith 在其主体中支持一组 LINQ 运算符。所以只需添加OrderBy

var query = 
    from s in Sectors.LoadWith(s => s.Subsectors.OrderBy(x => x.SectorId))
    orderby s.Name
    select s;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-17
    • 1970-01-01
    • 2012-12-16
    • 2015-03-21
    • 1970-01-01
    相关资源
    最近更新 更多