I have Three Table ApplicationUser, Posts, Comments
there is a one to many between users and Posts
there is a one to many between Posts and Comments
these Relations Has CasCade Delete and working Successfully
but when i'm trying to add a Relation Between one to many between Users And Comments for registering who has Creating This Comment , i want when deleting the user Also his comments being deleted
but it give me this error Introducing FOREIGN KEY constraint 'FK_AcademyPosts_AspNetUsers_AcademyId' on table 'AcademyPosts' 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.
this is my code
ApplicationUser Model Code
public virtual ICollection<Comments> Comments { get; set; }
Comments Model Code
public ApplicationUser User { get; set; }
public string UserId { get; set; }
Configuration Code
builder
.HasOne(user => user.User)
.WithMany(comment => comment.Comments)
.HasForeignKey(user => user.UserId)
.OnDelete(DeleteBehavior.Cascade);
It is a cascade deleting issue when using EF Core, and it is the restriction of MS SQL Server itself.
Your one-to-many relationship of the three tables will enable cascade deleting of user – post – comment, meanwhile your new relationship of user/comment will also delete the comment when delete the comment, which is not allowed in the server.
Your configuration enables the cascade deleting between user and comments, and we’d better avoid it.
Then you need to manually modify the deleting method.
Load the commentto cascade delete.Create a new app and database cause in my test the migration history will affect the database and the error always exists.
You can also refer to the official document, which has a sample that is exactly the same with your problem. https://learn.microsoft.com/en-us/ef/core/saving/cascade-delete