显示具有自引用外键的组中的对象列表
本文关键字:对象 列表 自引用 显示 | 更新日期: 2023-09-27 18:29:05
我有一个模型,它包含一组任务:
public class model
{
public int id {get;set;}
public virtual ICollection<task> tasks {get;set;}
}
任务是这样建模的:
public class task
{
public int id {get;set;}
public byte category_id { get; set; }
public virtual category category { get; set; }
}
类别是这样建模的:
public class category
{
public byte category_id { get; set; }
public string category_name { get; set; }
public byte? parent_category_id { get; set; }
}
在我的MVC应用程序中,我有模型的Details页面,其中包括任务的集合。我想显示与模型相关的任务列表,按类别分组,如下所示:
- 类别1
- 任务1
- 任务2
- 子类别1
- 任务3
- 任务4
- 类别2
等等
一些任务直接链接到类别中,而另一些则位于子类别中。
我已经尝试了无数种"Model.GroupBy(x=>x.category_id)",并尝试在task.category.parent_category_id!=空,但我在这里很挣扎。
有什么更好的方法可以做到这一点?我太差劲了!
由于您的数据结构似乎是层次分明的,所以我会考虑使用Composite模式。
然后,您的任务将存储在类别中,类别也可以存储其他类别。作为树根的模型将只包含父类别的列表,而不是任务。
通过这种方式,您可以轻松地遍历树,并以递归的方式打印出层次结构。
你的复合图案可能看起来像:
// base class for composition
public abstract class Composite
{}
// category, can either hold tasks or other categories
public class Category : Composite
{
// list of child items, either tasks or categories
ICollection<Composite> Children { get; set;}
}
// task is a leave node in the hierarchy
public class Task : Composite
{}
// model will only hold categories
public class Model
{
ICollection<Category> Categories { get; set;}
}