I'm working on a practice app with .NET 6 and EF Core and I'm trying to implement a followers system. However I'm having issues with setting up the onDelete for the join-table:
This is my Profile class:
public class Profile {
public int Id {get; set;}
public string Email { get; set; }
public ICollection<ProfileFollowing> Followers { get; set; }
public ICollection<ProfileFollowing> Followings { get; set; }
}
And this Is my Join Table, which keeps records of the followings:
public class ProfileFollowing {
public int ObserverId { get; set; }
public Profile Observer { get; set; }
public int TargetId { get; set; }
public Profile Target { get; set; }
}
I'm setting this up in my model builder the following way:
modelBuilder.Entity<ProfileFollowing>(profileFollowing =>
{
profileFollowing
.HasOne(o => o.Observer)
.WithMany(p => p.Followings)
.HasForeignKey(o => o.ObserverId)
.OnDelete(DeleteBehavior.Cascade);
profileFollowing
.HasOne(t => t.Target)
.WithMany(p => p.Followers)
.HasForeignKey(t => t.TargetId)
.OnDelete(DeleteBehavior.Cascade);
profileFollowing.HasIndex(pf => new {pf.ObserverId, pf.TargetId}).IsUnique();
});
However, apparently SQL Server does not like when both on the onDelete are marked as cascades as this May Cause Cycles Or Multiple Cascade Paths. The idea of multiple cascades is that when I delete a Profile it may attempt to delete the same records in my ProfileFollowings table twice, right?
Well is there any workaround for this? I see the very same implementation (i.e. this one or a similar one), however nobody mentions the issues with deleting the records. I want to be sure that if I delete a Profile, the ProfileFollowings will update correctly and all of the other Profiles will have their followers/followings adjusted.
PS: I know one workaround would be to set one of the FK (TargetId/ObserverId) to null and set onDelete action to be SetNull, but this way my unique index on ObserverId & TargetId becomes useless.