Circular Reference Entity Framework

Çağlar Can SARIKAYA
1 min readMar 25, 2024

--

I had always gotten this error but I understand this at the end :D

I have a user class, an experience class, and a comment class.

    #region Experience

builder.Entity<Experience>(b =>
{
b.ToTable("Experiences");
});

builder.Entity<Experience>()
.HasOne(e => e.User)
.WithMany(u => u.Experiences)
.HasForeignKey(e => e.UserId)
.OnDelete(DeleteBehavior.Cascade);
#endregion

#region Comment

builder.Entity<Comment>(b =>
{
b.ToTable("Comments");
});

builder.Entity<Comment>()
.HasOne(c => c.User)
.WithMany(u => u.Comments)
.HasForeignKey(c => c.UserId)
.OnDelete(DeleteBehavior.Cascade);

builder.Entity<Comment>()
.HasOne(c => c.Experience)
.WithMany(e => e.Comments)
.HasForeignKey(c => c.ExperienceId)
.OnDelete(DeleteBehavior.Cascade);

#endregion

so here the circular ref :D there is a user, experience and comment relation.
Read carefully. the problem is really circular.
look that delete behavior which I am not using like that, always softdelete but I used this for enplain.

exp settings -> if the user will be deleted. it will delete related experience

comment settings -> if the experience is deleted. it will delete related comments also if the user is deleted, it will delete related comments.

so this part is works twice, if you delete a user, you will delete all experiences(as we declared in rule), also it will delete all comments.
but when experience is deleted it also!!!!! delete the comments, so it wants to delete comment table twice. You have to disable it one of them rules.

builder.Entity<Comment>()
.HasOne(c => c.User)
.WithMany(u => u.Comments)
.HasForeignKey(c => c.UserId)
.OnDelete(DeleteBehavior.Restrict);

I changed user comment relation to restrict(do nothing). It will delete ofcource because if a user will deleted it triggers to delete all related experiences, when experience is deleted, it delete all related comments.

so there is no circular now :)

--

--