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?
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With