ASP.NET 5(MVC6)EF7外键可能会导致循环

时间:2016-02-20 05:02:37

标签: asp.net asp.net-core-mvc entity-framework-core

这是我的模特:

public class Post
{

    [Key]
    public int PostId { get; set; }

    [Required]
    [MaxLength(140)]
    public string Title { get; set; }

    [Required]
    public string ApplicationUserId { get; set; }

    public ApplicationUser ApplicationUser { get; set; }
    public ICollection<Comment> Comments { get; set; }
}

public class Comment
{
    [Key]
    public int CommentId { get; set; }

    [Required]
    [StringLength(1000)]
    public string Text { get; set; }

    [Required]
    public int PostId { get; set; }

    [Required]
    public string ApplicationUserId { get; set; }


    public Post Post { get; set; }
    public ApplicationUser ApplicationUser { get; set; }

}

我收到错误:

  

介绍FOREIGN KEY约束&#39; FK_Comment_Post_PostId&#39;在桌子上&#39;评论&#39;可能会导致循环或多个级联路径。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束。   无法创建约束或索引。查看以前的错误。

这正是它们documents中的演示方式。

现在,如果我删除:

[Required]
public int PostId { get; set; }

并按如下方式使用Fluent API:

builder.Entity<Comment>().HasOne(p => p.Post).WithMany(c => c.Comments).IsRequired();

我仍然得到同样的错误。如果我明确说明

builder.Entity<Comment>().HasOne(p => p.Post).WithMany(c => c.Comments).IsRequired().OnDelete(DeleteBehavior.Cascade);

我仍然得到同样的错误。

如果我使用以下内容:

builder.Entity<Comment>().HasOne(p => p.Post).WithMany(c => c.Comments);

可以在没有帖子的情况下输入评论。评论必须属于帖子。

我错过了什么吗?这是一个常见的用例,与PK所需的FK的1对多关系。

1 个答案:

答案 0 :(得分:10)

我确实错过了一些东西。我的结构是用户可以拥有帖子。帖子可以有评论。由于评论也有用户,这就是造成循环问题的原因。

当删除帖子时,它会级联删除评论。这就是我们想要的。

删除用户时,会将删除级联到帖子和评论。但是帖子也会尝试级联删除评论。

我使用的解决方案是删除从用户到评论的级联删除。

这可以通过以下方式完成:

builder.Entity<Comment>().HasOne(c => c.ApplicationUser).WithMany(u => u.Comments).IsRequired().OnDelete(DeleteBehavior.Restrict);