我想了解如何爲分層數據構建自引用模型。最終我將創建一個類別樹。如何爲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