簡體   English   中英

EF6代碼優先:MySqlException:無法添加或更新子行:外鍵約束失敗

[英]EF6 Code First: MySqlException: Cannot add or update a child row: a foreign key constraint fails

我先使用Entity Framework 6代碼

我有一個帶有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”)參考“ propertyforsale_predictions”(“ pid”))

我無法弄清楚如何指定外鍵,以便可以添加屬性數據而不添加其他2個表中的數據?

為什么要使用導航屬性? 如果您不打算進行延遲加載,則可能要擺脫虛擬屬性,然后對那些對象使用顯式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;

或者您可能想在其他任何地方查看正在執行的實際查詢。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM