我使用實體框架7 RC1和我有實體:INSERT語句衝突與外鍵約束「FK_PostTag_Tag_TagId」
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; }
}
該機型配置了這些實體如下:
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);
});
}
我創建了遷移和數據庫。然後我試圖創建一個帖子:
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.
有誰知道這個錯誤的原因是什麼?
但是我想在我的模型上使用FK ...我總是有幾個查詢它是真的有用...順便說一句,我從來沒有與EF 6這個問題... –
在這種情況下,你有使您的外鍵可以爲空。在你的例子中,你的PostId將爲0,這是打破FK約束,因爲我猜你沒有0作爲DB中的PostId。 –
我得到了同樣的錯誤,甚至使兩個鍵可空... –