使用实体框架的ASP.NET MVC 3自参考模型 [英] Self referencing model in ASP.NET MVC 3 using Entity Framework

查看:108
本文介绍了使用实体框架的ASP.NET MVC 3自参考模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类别的类,它可以引用自身(只有一个级别)作为父类。

I have a category class and it can reference itself(only one level up) as parent category.

当我检索使用的DbContext使用实体框架的数据,父母关系不加载。我如何去实现呢?
这里是类

When I retrieve the data using dbContext using Entity Framework, the parent relationship is not loaded. How do I go about achieving that? Here is the class

public class Category
{
    [Key]
    public int CategoryID { get; set; }       
    [Display(Name="Category Name")]
    public string CategoryName { get; set; }

    public int ParentCategoryID { get; set; }
    public virtual Category ParentCategory { get; set; }

}

当我检索使用的DbContext所有类别中,ParentCategory为null B / C它没有加入与同一ID的另一个范畴类。

when I retrieve all Category using dbcontext, the ParentCategory is null b/c it didn't join to another Category class with same ID.

谁能告诉我我该怎么改db.Category.ToList()方法,因此也加入在同一时间的父子关系?谢谢

Can anyone tell me how do I change db.Category.ToList() method so it also joins the parent child relation at the same time? Thanks

推荐答案

尝试像这样

public class Category
{
    [Key]
    public int CategoryID { get; set; }       

    [Display(Name="Category Name")]
    public string CategoryName { get; set; }

    public int? ParentCategoryID { get; set; }
    public virtual Category ParentCategory { get; set; }

}

而在你的Context类,

And in your Context class,

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
  {
    modelBuilder.Entity<Category>().
      HasOptional(e => e.ParentCategory).
      WithMany().
      HasForeignKey(m => m.ParentCategoryID);
  }

这篇关于使用实体框架的ASP.NET MVC 3自参考模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆