简体   繁体   中英

How to sort a child list in Linq2DB?

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).

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM