Home > Blockchain >  How to sort a child list in Linq2DB?
How to sort a child list in Linq2DB?

Time:12-17

I have a table where each row owns a set of rows from another table, using LinqToDB.Mapping classes.

[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; }
}

I have worked out how to use the Association header to automatically load all the child objects when loading a list of the parent objects.

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

How do I set a sort order for the Subsectors list?

I can sort it later, but it would be nice to have the sorting done by the database.

There doesn't seem to be a property of the Association attribute for this, and adding to the orderby line would sort the parent objects (if it even worked).

CodePudding user response:

LoadWith supports a set of LINQ operators in its body. So just add OrderBy.

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