加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 07:29:46 所属栏目:asp.Net 来源:网络整理
导读:这是我的模特: 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; se
这是我的模特:

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

}

我收到错误:

Introducing FOREIGN KEY constraint ‘FK_Comment_Post_PostId’ on table ‘Comment’ 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.

这正是它们在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对多关系.

解决方法

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

删除帖子后,它会级联删除评论.这就是我们想要的.

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

我使用的解决方案是删除从User到Comment的级联删除.

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读