The INSERT statement conflicted with the FOREIGN KEY constraint “FK_PostTag_Tag_TagId”

冷暖自知 提交于 2019-12-01 01:54:22
m.phobos

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

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

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

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.

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.

I would say that you don't need to explicitly declare your foreign keys in EF CodeFirst the framework will handle it for you. So remove these properties from the PostTag class

public Int32 PostId { get; set; }
public Int32 TagId { get; set; }

And then remove these two lines from your configuration then try the save again. You will probably need to update your DB Model before saving.

b.HasKey(x => new { x.PostId, x.TagId });
b.HasOne(x => x.Post).WithMany(x => x.PostsTags).HasForeignKey(x => x.PostId);
b.HasOne(x => x.Tag).WithMany(x => x.PostsTags).HasForeignKey(x => x.TagId);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!