使用自身具有外键/导航键的模型类
我正在尝试在 ASP.NET MVC 3 中开发一个目录项目,并首先使用 EF Code 和现有数据库。我的数据库中有一个指向自身的类别表。为此,我编写了以下模型类。 --“如果模型错误,请纠正我”--
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 为空。请告诉我您将如何使用此代码或任何可以帮助我理解在这种情况下工作的资源。使用上述模型的任何类型的代码都会有所帮助,例如显示列表或菜单或任何内容。
I am trying to develop a catalog project in ASP.NET MVC 3 and using EF Code first with an existing Database. There is a Categories table in my database that points to itself. For that, I have written the following model class. --"Correct me if the model is wrong"--
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; }
}
Question : I am unable to understand as to how can i work with this class. While using and passing the following code to the view
var cat = dbStore.Categories.Include("ParentCategory").ToList()
.
I got this error : Object reference not set to an instance of an object. This is happening because the root category has null ParentCategoryID. Please tell me how will you work with this code or any resource that can help me understand working in such scenarios. Just any sort of code will be helpful that uses the above the model, like displaying a list or a menu or anything, just anything.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通常,您所做的就是从顶级类别移动到底层类别。为了做到这一点,首先您需要在类中定义
SubCategories
集合然后检索顶级类别
之后您可以遍历层次结构
Usually what you do is travel from top level categories to bottom level categories. Inorder to do that first you need to define
SubCategories
collection in your classThen you retrieve the top level categories
After that you can traverse the hierachey
如果您没有太多类别,您可以通过加载整个类别集合来解决此问题。我认为 EF 会为您处理修复问题,以便所有关系都正确填充。
据我所知,没有 SQL'ish 数据库/ORM 可以很好地处理这种情况。我经常使用的一种方法是加载整个集合,如上所述,然后手动修复关系。但我确实认为 EF 会为你做到这一点。
基本上你应该这样做:
If you do not have very many categories you can solve this by loading the whole collection of categories. I think EF will handle the fixup for you so all relations are properly populated.
As far as I know there are no SQL'ish databases/ORM's that can handle this scenario well. An approach I often use is to load the whole collection as I said above and then manually fix the relations. But I do think EF will do that for you.
Basically you should do: