【发布时间】: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