且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

INSERT语句与FOREIGN KEY约束“ FK_PostTag_Tag_TagId”冲突。

更新时间:2023-02-25 21:54:49

我遇到了同样的问题。这是我想出的解决方案。 这个 SO问题对我有很大帮助。

I had the same problems. Here's the solution I came up with. This SO question helped me a lot.

首先,添加 public DbSet< Tag>标签{get;设置;} 到您的 Context 类(如果缺少)。

First of all, add a public DbSet<Tag> Tags {get; set;} to yout Context class if it's missing.

然后修改帖子创建如下

Context context = new Context();
var tmpTag = new Tag { Name = "Tag name" } //add the tag to the context
context.Tags.Add(tmpTag);

Post post = new Post {
    PostsTags = new List<PostTag>(), // initialize the PostTag list
    Title = "Post title"
};    
context.Posts.Add(post);

var postTag = new PostTag() {Post = post, Tag = tag}; // explicitly initialize the PostTag AFTER addig both Post and Tag to context
post.PostTags.Add(postTag); // add PostTag to Post

await _context.SaveChangesAsync();

同时添加 post 标签 context.Posts context.Tags 之前, PostTag 对象允许EF在写入基础数据库时正确管理ID。

Explictly adding both post and tag to context.Posts and context.Tags before attempting to create the PostTag object allows EF to correctly manage the IDs while writing to the underlying DB.

为了完整性,解决了多对多关系管理的这一部分之后,我目前正在使用CascadeDelete Entity Framework Core(EF7)挣扎,但这是另一回事。

For the sake of completeness, after solving this part of the many-to-many relationship management, I'm currently struggling with CascadeDelete Entity Framework Core (EF7), but that's a different story.