我想了解如何为分层数据构建自引用模型。最终我将创建一个类别树。如何为asp.net MVC中的分层数据构建自引用模型对象?
我什么都没有在表格中。在我确定了结构后,我将创建表格。我现有对象的定义如下:
public class Categories
{
public Int64 catID { get; set; }
public Int64? parentCatID { get; set; }
public string catName { get; set; }
public string catDescription { get; set; }
}
我的假库填充类别是这样的:
// Fake hardcoded list of categories
private static IQueryable<Categories> fakeCategories = new List<Categories> {
new Categories { catID = 1, parentCatID = null, catName = "Root", catDescription = "" },
new Categories { catID = 2, parentCatID = 1, catName = "Category w/subs", catDescription = "" },
new Categories { catID = 3, parentCatID = 1, catName = "Category no subs but now has subs", catDescription = "" },
new Categories { catID = 4, parentCatID = 2, catName = "Zub Cat", catDescription = "" },
new Categories { catID = 5, parentCatID = 2, catName = "Sub Cat", catDescription = "" },
new Categories { catID = 6, parentCatID = null, catName = "Another Root", catDescription = "" },
new Categories { catID = 7, parentCatID = null, catName = "Ze German Root", catDescription = "" },
new Categories { catID = 8, parentCatID = 3, catName = "Brand new cats", catDescription = "" },
new Categories { catID = 9, parentCatID = 8, catName = "Brand new cats sub", catDescription = "" },
}.AsQueryable();
我停留在如何让这个自参考对象,我可以发送到视图显示。我在想,控制器会是这样的:
public ActionResult CategoryTree()
{
var cats = fakeRepository.Categories.ToList();
return View(cats);
}
我不知道我是否正确接近这个。我会使用递归的自定义HtmlHelper方法来显示类别树。
我该如何获得Categories
作为自引用对象?
编辑:改写的问题
我开始想,我问是在我头上:-)
问题,请检查验证码:
[Table]
public class Category
{
[Column(IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.OnInsert)]
public Int64 catID { get; set; }
public Int64? parentCatID { get; set; }
public string catName { get; set; }
public string catDescription { get; set; }
internal EntityRef<Category> _category;
[Association(ThisKey = "parentCatID", Storage = "_category")]
public Category category {
get { return _category.Entity; }
internal set { _category.Entity = value; }
}
}
此代码编译,我不必更改我的假库。我觉得我很想念一些东西。我不知道如何测试这个看看它是否有效。我正在推动我的知识极限。
我甚至不确定正确的问题是什么。我要去玩这个...看看我是否有错误,或者它是否按我期望的方式工作。我可能会再次在这里编辑。
编辑2
看来,Category.category
只是返回null。而且,它似乎不在任何类型的列表中。我不确定我是否正确建立关系。
有什么想法?
你想如何查询你正在使用的数据?它会从最低点起? – WestDiscGolf 2010-09-09 17:37:29
嗯......自上而下??? root-to-subcat -to-subsubcat - etc – quakkels 2010-09-09 18:07:33