INSERT 语句与 FOREIGN KEY 约束“FK_PostTag_Tag_TagId"冲突 [英] The INSERT statement conflicted with the FOREIGN KEY constraint "FK_PostTag_Tag_TagId"

查看:21
本文介绍了INSERT 语句与 FOREIGN KEY 约束“FK_PostTag_Tag_TagId"冲突的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Entity Framework 7 RC1 并且我有实体:

I am using Entity Framework 7 RC1 and I have the entities:

public class Post {
  public Int32 Id { get; set; }
  public String Title { get; set; }
  public virtual IList<PostTag> PostsTags { get; set; }
}

public class Tag {
  public Int32 Id { get; set; }
  public String Name { get; set; }
  public virtual IList<PostTag> PostsTags { get; set; }
}

public class PostTag {
  public Int32 PostId { get; set; }
  public Int32 TagId { get; set; }
  public virtual Post Post { get; set; }
  public virtual Tag Tag { get; set; }
}

这些实体的模型配置如下:

The model configuration for these entities is the following:

protected override void OnModelCreating(ModelBuilder builder) {

  base.OnModelCreating(builder);

  builder.Entity<Post>(b => {

    b.ToTable("Posts");
    b.HasKey(x => x.Id);
    b.Property(x => x.Id).UseSqlServerIdentityColumn();
    b.Property(x => x.Title).IsRequired().HasMaxLength(100);
  });

  builder.Entity<Tag>(b => {
    b.ToTable("Tags");
    b.HasKey(x => x.Id);
    b.Property(x => x.Id).UseSqlServerIdentityColumn();
    b.Property(x => x.Name).IsRequired().HasMaxLength(100);
  });

  builder.Entity<PostTag>(b => {
    b.ToTable("PostsTags");
    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);
  });

}

我创建了迁移和数据库.然后我尝试创建一个帖子:

I created the migration and the database. Then I tried to create a post:

  Context context = new Context();

  Post post = new Post {
    PostsTags = new List<PostTag> {
      new PostTag {
        Tag = new Tag { Name = "Tag name" }
      }
    },
    Title = "Post title"
  };

  context.Posts.Add(post);

  await _context.SaveChangesAsync();

保存时出现以下错误:

An error occurred while updating the entries. 
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_PostTag_Tag_TagId". 
The conflict occurred in database "TestDb", table "dbo.Tags", column 'Id'. 
The statement has been terminated.

有人知道这个错误的原因吗?

Does anyone knows the reason for this error?

推荐答案

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

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.

这篇关于INSERT 语句与 FOREIGN KEY 约束“FK_PostTag_Tag_TagId"冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆