Recursive Hierarchical Parent child

前端 未结 3 1830
遇见更好的自我
遇见更好的自我 2021-02-10 01:13

I have a collection of items coming from a database which has a parentid value or null.

Here is my class design:

public class Item
{
public          


        
3条回答
  •  南笙
    南笙 (楼主)
    2021-02-10 01:49

    Do you really need a setter for sub items? Also be mindful of the performance issues when you run Select* queries on SQL server.

      public List SubItems{
      get
      {
       try{
            var validParents = db.items.Where(x=>x.ParentId!=null && x.ParentId.Equals(Id)); //db is your dbcontext
            if(validParents !=null)
            {
               return validParents.ToList(); 
            }else
            {
             return null;
            } 
            catch(Exception)
            {
              return null;
            }
       }
    

    (Note: Think of adding this to your partial entity class. Never name your entity as "Item" :).Item is a reserved word. )

提交回复
热议问题