Entity Framework Core 8 dbcontext - 无法在多对多关系中添加一些行

问题描述 投票:0回答:1

有人可以解释一下为什么我会收到此错误吗

INSERT 语句与 FOREIGN KEY 约束“FK_ArticleTag_Tags_ArticleId”冲突。冲突发生在数据库“Blog”,表“dbo.Tags”,列“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; }
}

迁移后,有 50 篇文章和 20 个标签,我无法向(自动生成的)

ArticleTag
表添加新行,其中
ArticleId
大于 20。

我不知道这是怎么回事,有人可以向我解释我做错了什么吗?

c# entity-framework-core
1个回答
0
投票

连接表的外键链接不正确 -

TagId
Articles.ArticleId
以及
ArticleId
Tags.TagId
。也可以在错误消息或生成的迁移中看到。当然,在模型中,如果你仔细看的话 - 我不喜欢
ForeignKey
属性的原因之一是它的多用途和不同的含义,具体取决于你应用它的位置,因此很容易出错。

您需要更正模型并生成/应用新的迁移:

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; }
}
© www.soinside.com 2019 - 2024. All rights reserved.