【发布时间】:2011-10-02 13:01:02
【问题描述】:
我正在尝试在 ASP.NET MVC 3 中开发一个目录项目,并首先将 EF 代码与现有数据库一起使用。我的数据库中有一个 Categories 表指向它自己。为此,我编写了以下模型类。 --“如果模型错误,请纠正我”--
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; }
}
问题:我无法理解如何使用这门课。在使用以下代码并将其传递给视图时
var cat = dbStore.Categories.Include("ParentCategory").ToList()。
我收到此错误:对象引用未设置为对象的实例。发生这种情况是因为根类别的 ParentCategoryID 为空。请告诉我您将如何使用此代码或任何可以帮助我理解在这种情况下工作的资源。使用上述模型的任何类型的代码都会有所帮助,例如显示列表或菜单或任何东西,任何东西。
【问题讨论】:
标签: entity-framework-4.1 ef-code-first entity-relationship code-first hierarchical-data