Self referencing model in ASP.NET MVC 3 using Enti

2019-08-28 00:15发布

问题:

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

}