Entity Framework Core 8 dbcontext - can't add some rows in many-to-many relationship

34 views Asked by At

Can someone explain me why I get this error

INSERT statement conflicted with the FOREIGN KEY constraint "FK_ArticleTag_Tags_ArticleId". The conflict occurred in database "Blog", table "dbo.Tags", column 'TagId'"

public class Article
{
    public Article()
    {
        Comments = new HashSet<Comment>();
        Tags = new HashSet<Tag>();
    }

    [Key]
    public int ArticleId { get; set; }
    public int? CategoryId { get; set; }

    [StringLength(30)]
    public string ArticleName { get; set; } = null!;
    public string? ArticleDescription { get; set; }
    public bool Visibility { get; set; }

    [ForeignKey("CategoryId")]
    [InverseProperty("Articles")]
    public virtual Category Category { get; set; }
    [InverseProperty("Article")]
    public virtual ICollection<Comment> Comments { get; set; }
    [ForeignKey("TagId")]         
    [InverseProperty("Articles")] 
    public virtual ICollection<Tag> Tags { get; set; }
}

public class Tag
{
    public Tag() 
    { 
        Articles = new HashSet<Article>();
    }

    [Key]
    public int TagId { get; set; }
    [Required]
    [StringLength(50)]
    public string Title { get; set; }

    [ForeignKey("ArticleId")]
    [InverseProperty("Tags")]
    public virtual ICollection<Article>? Articles { get; set; }
}

After migration, with 50 articles and 20 tags, I cannot add a new row to (autogenerated) ArticleTag table where ArticleId is greater than 20.

I have no idea what this is about, can someone explain to me what I'm doing wrong?

1

There are 1 answers

0
Ivan Stoev On BEST ANSWER

Foreign keys of the join table are linked incorrectly - TagId to Articles.ArticleId and ArticleId to Tags.TagId. It can also be seen in the error message or the generated migration. And of course in the model in case you look carefully - one reason I don't like ForeignKey attribute is its multipurpose and different meanings depending on where you apply it, thus very error prone.

You need to correct the model and generate/apply new migration:

public class Article
{    
    [ForeignKey("ArticleId")] // <-- was [ForeignKey("TagId")]
    [InverseProperty("Articles")]
    public virtual ICollection<Tag> Tags { get; set; }
}

public class Tag
{
    [ForeignKey("TagId")] // <-- was [ForeignKey("ArticleId")]
    [InverseProperty("Tags")]
    public virtual ICollection<Article> Articles { get; set; }
}