简体   繁体   中英

Cascade delete on one to many relation with same entity

I have a Comment entity where a new comment has no parent but a list of Replies which is also a Comment with Required Parent.

A user can create a comment then other user can reply to that comment which will be parent of all these replies and replies can also have further replies with a parent comment for every reply.

How do I cascade delete the replies of each comment so that all the replies and their further replies are deleted automatically when I delete a comment or reply of that comment.

Here is the Comment Model:

public class Comment
{
    public Comment()
    {
        Replies = new List<Comment>();
    }
    [Required]
    public int CommentId { get; set; }

    public ApplicationUser User { get; set; }
    [Required]
    public DateTime Datetime { get; set; }      
    [Required]
    public string Audio { get; set; }

    public Post Post { get; set; }

    [JsonIgnore]
    public List<Comment> Replies { get; set; }

    public Comment Parent { get; set; }
}

Here is What I tried with Fluent API

modelBuilder.Entity<Comment>().
            HasMany(s => s.Replies).
            WithRequired(s => s.Parent).
            WillCascadeOnDelete(true);

It throws following errors

Introducing FOREIGN KEY constraint 'FK_dbo.Comments_dbo.Comments_Parent_CommentId' on table 'Comments' 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.

You would have to change to SQL table like

ALTER TABLE Comment ADD CONSTRAINT FK_dbo.Comments_dbo.Comments_Parent_CommentId FOREIGN KEY (CommentId) REFERENCES T1 (CommentId)
ON DELETE CASCADE;

The last bold part is the key.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM