【问题标题】:The Insert statement conflict with the foreign key constraint. Entity Framework errorInsert 语句与外键约束冲突。实体框架错误
【发布时间】:2015-11-01 23:32:17
【问题描述】:

我正在尝试创建一对多关系,其中 TypeOfImmobile 可以有一个或多个 Immobile。 这是我的模型类:

public class TypeOfImmobile
{
    public int Id { get; set; }
    [Display(Name = "Type Of Immobile")]
    public string Designation { get; set; }

    public ICollection<Immobile> Immobiles { get; set; }
}

public class Immobile
{
    public int Id { get; set; }
    public int TypeOfImmobileId { get; set; }
    public virtual TypeOfImmobile TypeOfImmobile { get; set; }
}

创建 Immobile 时发生错误:

INSERT 语句与 FOREIGN KEY 约束“FK_dbo.Immobiles_dbo.TypeOfImmobiles_TypeOfImmobilesId”冲突。冲突发生在数据库“aspnet-ARQSI-IT2-2015103105205​​6”、表“dbo.TypeOfImmobiles”、“Id”列中。 声明已终止。

【问题讨论】:

  • 确切的错误是什么?
  • public virtual ICollection&lt;Immobile&gt; Immobiles { get; set; } 也许你错过了virtual
  • 我试过虚拟它不起作用:/
  • 您究竟是如何创建 Immobile 的?你能给我们看看代码吗?
  • 如果您仍然需要答案,您应该显示导致异常的代码。

标签: c# asp.net entity-framework


【解决方案1】:

您的TypeOfImmobileId 属性类型为int,因此您不能将其设置为null。即使您没有为integer 赋值,它也将等于0 而不是null。如果您在创建命令发送到 SQL 时没有为 TypeOfImmobileId 分配值,则 SQL 将在创建记录的存储过程中将其视为 0。并且可能 TypeOfImmobile 表的主键中不包含具有0 值的记录。也就是说,您发送的数据的外键值是无效的。它不对应 TypeOfImmobile 表中的任何主键值。您的主键不应为空,但外键应可为空。

您应该将TypeOfImmobileId 的类型从int 更改为Nullable&lt;int&gt; 或只是int?

所以TypeOfImmobileId 属性应该是这样的:

public int? TypeOfImmobileId { get; set; }

您不需要将ForeignKey 属性添加到TypeOfImmobileId 属性,因为您关注Code-First conventionsname of Foreign Key matches with name of Primary Key of related entity

您可以在运行 SQL Server Profiler 时观察到问题。当应用程序运行将创建记录的命令时,将列出相关的存储过程。

【讨论】:

  • 嗨,很高兴您加入我们的实体框架标签。一个小提示。通常,回答不清楚的问题是一个非常绝望的操作。这个问题不清楚,因为它没有显示导致异常的代码。我不认为 FK 应该可以为空。我们确实需要查看代码来判断问题所在。
  • 对我有帮助 谢谢!
【解决方案2】:

这是由以下原因之一引起的:

1-您没有设置导航属性 (TypeOfImmobile) 或 TypeOfImmobileId

2-TypeOfImmobileId 或 TypeOfImmobile 的值在数据库中不存在

3-也许您在保存 TypeOfImmobile 之前先保存 Immobile

【讨论】:

    【解决方案3】:

    似乎在创建Immobile 时,您可能没有将TypeOfImmobileId 属性设置为有效值,即现有TypeOfImmobileId

    【讨论】:

      【解决方案4】:

      您需要在新的属性 ID Your_FK_ImmobileId 中通过 [ForeignKey("Your_FK_ImmobileId")] 设置 FK

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-29
        • 1970-01-01
        • 2019-01-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多