【问题标题】:The INSERT statement conflicted with the FOREIGN KEY (Code First Approach)INSERT 语句与 FOREIGN KEY 冲突(代码优先方法)
【发布时间】:2022-11-30 00:32:28
【问题描述】:

这些是我的课程:

public class Animal
{
    [Key]
    public int AnimalId { get; set; }

    public string Name { get; set; }
    public int Age { get; set; }
    public string Img { get; set; }
    public string Description { get; set; }

    public List<Comment> comments { get; set; }

    public int CategoryId { get; set; }

    [ForeignKey("CategoryId")]
    public Category Category { get; set; }   
}

public class Category
{
    public int CategoryId { get; set; }

    public string Name { get; set; }

    public Animal Animal { get; set; }
    List<Animal> animals { get; set; }
}

public class Comment
{
    public int CommentId { get; set; }

    public string Text { get; set; }

    public int AnimalId { get; set; }
    public Animal Animal { get; set; } 
}

我收到此错误:

INSERT 语句与 FOREIGN KEY 约束“FK_animals_categories_CategoryId”冲突。冲突发生在数据库“Local_PetShop”、表“dbo.categories”、“CategoryId”列中。

即使在动物创建页面中插入categoryid 值,我也无法保存数据库中的更改。

有任何想法吗?

【问题讨论】:

    标签: c# sql-server asp.net-mvc asp.net-core entity-framework-core


    【解决方案1】:

    您需要在所有表上设置主键。

    例如

    [钥匙] public int CategoryId { 得到;放; }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多