整理自引用关系 [英] sorting Self-Referencing Relationship
本文介绍了整理自引用关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设下面的模型。注意自引用关系父。
Assume the following model. Note the self-referencing relationship "parent".
public class Category
{
public virtual long Id { get; set; }
public virtual string Name { get; set; }
public virtual Category Parent { get; set; }
public virtual long? ParentId { get; set; }
}
我的数据如下:
My data are as follows:
id | name | parentId
1--------tag 1 ----- null
2--------tag 2 ----- 1
3--------tag 3 ----- 1
4--------tag 4 ----- 2
5--------tag 5 ----- null
6--------tag 6 ----- null
我想写如下:
tag 1
----->tag 2
----->----->tag 4
----->tag 3
tag 5
tag 6
这是我的代码
var categorys = __categories
.AsNoTracking()
.ToList();
我不知道如何将它们进行排序
I do not know how to sort them
推荐答案
试试这个递归函数
class Program
{
static void Main(string[] args)
{
using (var db = new aaContext2())
{
Temp temp = new Temp();
var cc = db.Catagory.FirstOrDefault();
IList<Category> parentList =new List <Category>();
foreach (Category catagory in db.Catagory.Where(cat => cat.ParentId == null))
{
parentList.Add(temp.Recursive(catagory.Id, catagory.Name));
}
}
}
}
public class Temp{
public Category Recursive(long parentId, string name)
{
Category catagory = new Category();
catagory.Id = parentId; catagory.Name = name;
using (var db = new aaContext2())
{
//base condition
if (db.Catagory.Where(catagory1 => catagory1.ParentId == parentId).Count() < 1)
{
return catagory;
}
else
{
IList<Category> newCatagoryList = new List<Category>();
foreach (Category cat in db.Catagory.Where(cata => cata.ParentId == parentId))
{
newCatagoryList.Add(Recursive(cat.Id, cat.Name));
}
catagory.CatagoryList = newCatagoryList;
return catagory;
}
}
}
}
public class aaContext2 : DbContext
{
public DbSet<Category> Catagory { get; set; }
}
public class Category
{
public virtual long Id { get; set; }
public virtual string Name { get; set; }
public virtual Category Parent { get; set; }
public virtual ICollection<Category> CatagoryList { get; set; }
public virtual long? ParentId { get; set; }
}
这篇关于整理自引用关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文