简体   繁体   English

级联删除与同一实体的一对多关系

[英]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. 我有一个Comment实体,其中新注释没有父级,但有一个答复列表,该列表也是带有必填父级的注释。

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 这是我尝试使用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. 在表“注释”上引入外键约束“ FK_dbo.Comments_dbo.Comments_Parent_CommentId”可能会导致循环或多个级联路径。 Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. 指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束。 Could not create constraint or index. 无法创建约束或索引。 See previous errors. 请参阅先前的错误。

You would have to change to SQL table like 您将不得不更改为SQL表,例如

ALTER TABLE Comment ADD CONSTRAINT FK_dbo.Comments_dbo.Comments_Parent_CommentId FOREIGN KEY (CommentId) REFERENCES T1 (CommentId) 更改表注释添加约束FK_dbo.Comments_dbo.Comments_Parent_CommentId外键(CommentId)参考T1(CommentId)
ON DELETE CASCADE; 删除级联时;

The last bold part is the key. 最后一个粗体部分是关键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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