4

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
bielu000
  • 1,826
  • 3
  • 21
  • 45

1 Answers1

10

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)
}
Amin Golmahalleh
  • 3,585
  • 2
  • 23
  • 36
devzero
  • 2,510
  • 4
  • 35
  • 55
  • Unfortunately in EF Core there is no HasOptional options. – bielu000 Sep 06 '17 at 19:20
  • I changed the syntax to EF 7. Nullable parentId should set it as optional – devzero Sep 06 '17 at 19:30
  • But it doesn't work. If I try update database, I have an exception: Introducing FOREIGN KEY constraint 'FK_Categories_Categories_ParentId' on table 'Categories' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could not create constraint or index. See previous errors. – bielu000 Sep 06 '17 at 19:53
  • Have you tried .WillCascadeOnDelete(false); ? – devzero Sep 06 '17 at 22:03
  • Should Subcategories have virtual keyword? – ddagsan Jun 07 '19 at 12:08
  • It does not matter in this context, you need virtual for EF to be able to create proxies for easier change tracking IE better performance. – devzero Jun 07 '19 at 12:59