简体   繁体   中英

Entity Framework: sort linked entities

Given the following entity class, which represents an item in a linked list of items, how can we sort using LINQ these items (in the order defined by NextItemId ) , such that the query is translated to SQL and done on the database side?

public class Item
{
    public virtual int Id { get; set; }
    public virtual string Title { get; set; } 

    public virtual int? NextItemId { get; set; }
    public virtual Item NextItem { get; set; }

}

I don't think it's possible. In my system, where I need to implement somewhat similar feature to this, I use an indexed varchar field to keep the full path of the item like

Id     NextItemId     ItemPath
1      2              /1
2      9              /1/2
9      13             /1/2/9

This way you can query by using where ItemPath.StartsWith() and utilise the index too.

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