I'm a relatively new programmer and I'm in the middle of creating Entities for Entity Framework Core for a project I'm currently on, but I'm having difficulty figuring out how to setup 1 specific entity named "Group".
The "Group" entity can contain zero to more groups as parents of it, and it can contain zero to more groups as its children.
i tried writing it the following way with the group class:
public class Group
{
public int GroupID { get; set; }
//Other properties here
public ICollection<SubGroup>? ParentGroups { get; set; }
public ICollection<SubGroup>? ChildGroups { get; set; }
}
with the SubGroup class looking like this:
public class SubGroup
{
public int ParentGroupID { get; set; }
public int ChildGroupID { get; set; }
public Group ParentGroup { get; set; }
public Group ChildGroup { get; set; }
}
alongside this piece of fluent API:
modelBuilder.Entity<SubGroup>().HasKey(sg => new { sg.ParentGroupID, sg.ChildGroupID });
modelBuilder.Entity<Group>().HasMany(g => g.ParentGroups).WithOne(sg => sg.ParentGroup).HasForeignKey(g => g.ParentGroupID).OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<Group>().HasMany(g => g.ChildGroups).WithOne(sg => sg.ChildGroup).HasForeignKey(g => g.ChildGroupID).OnDelete(DeleteBehavior.Restrict);
The thought process in my head is that subgroups should show which groups are children/parents of which groups. While i was able to generate a migration and update the database, i'm not entirely sure if this is how you're supposed to do it, so i've also thought about doing it the following way:
public class Group
{
public int GroupID { get; set; }
//Other properties here
public ICollection<Group>? ParentGroups { get; set; }
public ICollection<Group>? ChildGroups { get; set; }
}
alongside the following fluent API:
modelBuilder.Entity<Group>().HasMany(g => g.ChildGroups).WithMany(sg => sg.ParentGroups);
i want to ask anyone who's made this kind of relation before if i'm right or wrong in either case, and how it should be written. I hope anyone could help me here Thanks in advance
EDIT: I completely forgot to mention in the first case that the only reason I could update the database there was because I added .OnDelete(DeleteBehavior.Restrict)
to the end of the fluent API because it kept warning me with this:
Introducing FOREIGN KEY constraint 'FK_SubGroup_Group_ParentGroupID' on table 'SubGroup' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints
I want the group table rows to cascade and delete all subgroup relation rows associated with the deleted group without deleting the other end of the relation but don't know how in this case