Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Itself referention -> parent/child [duplicate]

Is it possible to set parent/child relations using EF Core and fluent api?

I have following class

public class Category 
{
   public int Id { get; set; }
   public int ParentId { get; set; }
   public string Name { get; set; }
   public ICollection<Category> SubCategories { get; set; }
}

So if I create list of objects with have structure as below, it is possible that, EF set entitie's id, and parentId with appropriate numbers?

  • Cat 1
    • Cat 2
      • Cat 3
    • Cat4
    • Cat5
like image 675
bielu000 Avatar asked Jan 04 '23 12:01

bielu000


1 Answers

You can just reference your own class:

public class Category 
{
   public int Id { get; set; }
   public int? ParentId { get; set; }
   public Category Parent { get; set; }
   public string Name { get; set; }
   public ICollection<Category> SubCategories { get; set; }
}

You can also set it up further with fluent api:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
  modelBuilder.Entity<Category>()
            .HasMany(j => j.SubCategories)
            .WithOne(j => j.Parent)
            .HasForeignKey(j => j.ParentId)
}
like image 157
devzero Avatar answered Jan 13 '23 11:01

devzero