如何忽略Entity Framework Core SQLite数据库中的外键约束?

the*_*ess 4 c# sqlite entity-framework-core

外键约束无法将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);
}
Run Code Online (Sandbox Code Playgroud)

我从Sqlite数据库中收到一个错误:

{“ SQLite错误19:'FOREIGN KEY约束失败'”]}

bri*_*lam 6

如果连接关闭,则PRAGMA会失去效果。您需要通过在调用之前和之后db.Database.OpenConnection()以及CloseConnection()在调用之后增加连接的生命周期。

您也可以optionsBiulder.UseSqlite(connectionString, x => x.SuppressForeignKeyEnforcement())通过自动打开每个连接的外键强制功能来调用EF。

  • 对于 EF Core 3.0,SuppressForeignKeyEnforcement 已被删除。请参阅 https://docs.microsoft.com/en-us/ef/core/what-is-new/ef-core-3.0/writing-changes#pragma 在连接字符串中使用“Foreign Keys = False”。例如。connectionString =“数据源=Data.db;密码=您的密码;外键=False” (6认同)