我正在尝试在 ASP.NET MVC 3 中开发一个目录项目,并首先将 EF 代码与现有数据库一起使用。我的数据库中有一个指向自身的类别 表。为此,我编写了以下模型类。 --“模型有误请指正”--
public class Category
{
public int CategoryID { get; set; }
public string CategoryName { get; set; }
public int? ParentCategoryID { get; set; }
public string CategoryDesc { get; set; }
[ForeignKey("ParentCategoryID")]
public virtual Category ParentCategory { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
问题:我无法理解如何使用此类。在使用以下代码并将其传递给 View 时
var cat = dbStore.Categories.Include("ParentCategory").ToList()
。
我收到此错误:未将对象引用设置为对象的实例。发生这种情况是因为根类别的 ParentCategoryID 为空。请告诉我您将如何使用此代码或任何可以帮助我理解在这种情况下工作的资源。使用上述模型的任何类型的代码都会有所帮助,例如显示列表或菜单或任何东西,任何东西。
最佳答案
通常您所做的是从顶级类别到底层类别。为此,您首先需要在类中定义 SubCategories
集合
public class Category
{
public int CategoryID { get; set; }
public string CategoryName { get; set; }
public int? ParentCategoryID { get; set; }
public string CategoryDesc { get; set; }
[ForeignKey("ParentCategoryID")]
public virtual Category ParentCategory { get; set; }
[InverseProperty("ParentCategory")]
public virtual ICollection<Category> SubCategories{ get; set; }
public virtual ICollection<Product> Products { get; set; }
}
然后您检索顶级类别
var topCategories = dbStore.Categories
.Where(category => category.ParentCategoryID == null)
.Include(category => category.SubCategories).ToList();
之后你可以遍历层次结构
foreach(var topCategory in topCategories)
{
//use top category
foreach(var subCategory in topCategory.SubCategories)
{
}
}
关于entity-framework-4.1 - 使用自身具有外键/导航键的模型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7626475/