如何忽略Entity Framework Core SQLite數據庫中的外鍵約束?

c# entity-framework-core sqlite

外鍵約束失敗使用SQLite和Entity Framework Core

我在桌子上有關係

[Table("organizations")]
public class Organizations
{
    [Column("id")]
    public int Id { get; set; }

    [Column("parent_id")]
    [ForeignKey("id")]
    public int? ParentId { get; set; }

    [Column("person_id")]
    public int? PersonId { get; set; }
 }


public DbSet<Organizations> Organizations { get; set; }

using (var db = new SQLiteDbContext($"Filename={dbPath};"))
{
    db.Database.ExecuteSqlCommand("PRAGMA foreign_keys=OFF;");
    db.Database.ExecuteSqlCommand("PRAGMA ignore_check_constraints=true;");
    db.Organizations.AddRange(organizationsResult.Rows);
}

我從Sqlite數據庫收到錯誤:

{“SQLite錯誤19:'FOREIGN KEY約束失敗'”}

一般承認的答案

如果連接關閉,PRAGMA會失效。您需要通過在之前和之後調用db.Database.OpenConnection()CloseConnection()來增加連接的生命週期。

您還可以調用optionsBiulder.UseSqlite(connectionString, x => x.SuppressForeignKeyEnforcement())來防止EF在每個連接上自動轉換外鍵執行。



Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow