且构网

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

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

更新时间:2023-02-25 22:12:14

我遇到了同样的问题.这是我想出的解决方案.这个所以问题对我帮助很大.

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

首先添加一个public DbSet;标签 {get;设置;} 到你的 Context 类,如果它丢失了.

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

然后修改post创建如下

Then modify the post creation as follows

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();

在尝试创建 posttagcontext.Postscontext.Tags 之前显式添加PostTag 对象允许 EF 在写入底层 DB 时正确管理 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.