【问题标题】:ASP.NET 5 (MVC6) EF7 Foreign Key may cause cyclesASP.NET 5 (MVC6) EF7 外键可能会导致循环
【发布时间】:2016-02-20 05:02:36
【问题描述】:

这是我的模型:

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; }

}

我收到错误:

在表 'Comment' 上引入 FOREIGN KEY 约束 'FK_Comment_Post_PostId' 可能会导致循环或多个级联路径。指定 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);

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

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

【问题讨论】:

  • 另外,请注意 ApplicationUser 的设置方式相同。但是这些列设置正确。

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


【解决方案1】:

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

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

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

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

这是通过以下方式完成的:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-26
    • 2010-10-25
    • 2015-10-26
    • 2020-12-26
    相关资源
    最近更新 更多