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

后端 未结 2 2030
余生分开走
余生分开走 2021-01-07 13:28

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

public class Post {
  public Int32 Id { get; set; }
  public String Title { get;          


        
2条回答
  •  失恋的感觉
    2021-01-07 14:06

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

提交回复
热议问题