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

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



Solution 1:[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);
  }

Solution 2:[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; }

}

Solution 3:[3]

public class Category
{

    public Guid Id { get; set; }
    public string Nom { get; set; }
    public string Description { get; set; }
    public ICollection<Category> SubCategory { get; set; } = new List<Category>();
    [JsonIgnore]
    public Category Parent { get; set; }
    public Guid? ParentId { get; set; }

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mr. Lumos
Solution 2 Eranga
Solution 3 Guedri Abdelkalek