Is recursive query possible in LINQ to Entities

前端 未结 3 1778
感动是毒
感动是毒 2020-12-10 07:28

this is my first question and sorry about my weak language.

I\'ve got a table like this model;

 public class Menu
 {
      [Key]
      public int ID          


        
3条回答
  •  余生分开走
    2020-12-10 08:00

    I will try something like this.

    This query will take all menu records from the database and will create dictionary with ParentId for key and all menus for specific parent id as values.

    // if you're pulling the data from database with EF
    var map = (from menu in ctx.Menus.AsNoTracking()
               group by menu.ParentId into g
               select g).ToDictionary(x => x.Key, x => x.ToList());
    

    Now we can iterate the parentIds and create MyMenu instances very easly

    var menusWithChildren = new List()
    foreach(var parentId in map.Keys)
    {
       var menuWithChildren = new MyMenu { ... }
       menuWithChildren.AddRange(map[parentId]);
    }
    

    Now you have list with the associations. This way you will have the children and parent associated by reference (no dublicate references across different nesting levels) But i wonder how do you define the roots, if you need to know them at all ? I don't know if this is suitable for you.

提交回复
热议问题