Self referencing model in ASP.NET MVC 3 using Entity Framework

和自甴很熟 提交于 2019-12-12 04:05:30

问题


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

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; }

}

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

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


回答1:


Try Like this

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; }

}

And in your Context class,

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



回答2:


The ParentCategoryID has to be nullable because the root category will not have a parent and EF needs to assign null to it.

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; }

}


来源:https://stackoverflow.com/questions/9024928/self-referencing-model-in-asp-net-mvc-3-using-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!