【问题标题】:EF6 Code First: MySqlException: Cannot add or update a child row: a foreign key constraint failsEF6 代码优先:MySqlException:无法添加或更新子行:外键约束失败
【发布时间】:2018-01-19 16:40:47
【问题描述】:

我正在使用 Entity Framework 6 Code First

我有一个带有其他 2 个表的属性表,可能可能不包含有关该属性的更多信息。

所以,换句话说。我可能只想将数据添加到属性表。

这是我的桌子模型:

public class PropertyForSale
{
    [Key]
    public int Id { get; set; }

    [Index("IX_pid", IsClustered = false, IsUnique = true, Order = 1), MaxLength(128)]
    public string pid { get; set; }
    public string Test { get; set; }

    [ForeignKey("pid")]
    public virtual PropertyForSale_Predictions PropertyForSale_Predictions { get; set; }
    [ForeignKey("pid")]
    public virtual PropertyForSale_Ratios PropertyForSale_Ratios { get; set; }
}

public class PropertyForSale_Predictions
{
    [Key, MaxLength(128)]
    public string pid { get; set; }
    public string Test { get; set; }
}

public class PropertyForSale_Ratios
{
    [Key, MaxLength(128)]
    public string pid { get; set; }
    public string Test { get; set; }
}

其中,视觉上看起来像这样:

当我尝试使用此代码向属性表添加信息时:

using (Model1 db = new Model1())
{
    db.PropertyForSale.Add(new Model.PropertyForSale
    {
        pid = "123",
        Test = "Test"
    });
    db.SaveChanges();
}

我收到此错误:

MySqlException: 无法添加或更新子行:外键约束失败 ("efcodefirstmysql"."propertyforsale", CONSTRAINT "FK_PropertyForSale_PropertyForSale_Predictions_pid" FOREIGN KEY ("pid") REFERENCES "propertyforsale_predictions" ("pid"))

我不知道如何指定外键,以便在其他 2 个表中添加属性数据没有数据?

【问题讨论】:

  • 如果您确实需要使用此设置,请不要指定这些外键中的任何一个。数据库服务器不能强制执行诸如“必须在某处......”之类的约束,所以不要告诉它这样做。
  • @tgz 但是当我调用数据时我不会有导航属性?喜欢 .Include("PropertyForSale_Predictions")?
  • 你试过去掉 ForeignKey 注释并使用 id 字段吗?看起来有点脏,但您并没有那样添加约束,我相信您的导航属性应该仍然没问题
  • 刚刚尝试删除 ForeignKey 注释,我得到了同样的错误:(
  • 数据库正在强制执行已经存在的约束,您应该从数据库中的表中删除外键。我会说只需使用更新的架构运行新的迁移。

标签: c# entity-framework ef-code-first


【解决方案1】:

为什么要使用导航属性?如果您不打算使用延迟加载,您可能希望摆脱虚拟属性,然后使用这些对象的显式 ID,您可以轻松跟踪和更新相关对象。这种方法将允许您插入 PropertyForSale,而不必担心您是否有匹配的预测和比率。

public class PropertyForSale
{
    [Key]
    public int Id { get; set; }

    [Index("IX_pid", IsClustered = false, IsUnique = true, Order = 1), MaxLength(128)]
    public string pid { get; set; }

    public string Test { get; set; }

    public int PropertyForSale_PredictionsId {get;set;}
    public PropertyForSale_Predictions PropertyForSale_Predictions { get; set; }

    public int PropertyForSale_RatiosId {get; set;}
    public PropertyForSale_Ratios PropertyForSale_Ratios { get; set; }
}

public class PropertyForSale_Predictions
{
    [Key, MaxLength(128)]
    public string pid { get; set; }

    public string Test { get; set; }

}

public class PropertyForSale_Ratios
{
    [Key, MaxLength(128)]
    public string pid { get; set; }

    public string Test { get; set; }

}

如果您有兴趣查看正在使用的查询,可以使用数据库日志输出到控制台窗口,方法是在执行 SaveChanges() 之前在 using 块中添加以下类似内容:

db.Database.Log = Console.WriteLine;

或者您可能希望查看正在执行的实际查询的其他任何地方。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-16
    • 2020-10-04
    相关资源
    最近更新 更多