【问题标题】:How to ignore Foreign Key Constraints in Entity Framework Core SQLite database?如何忽略 Entity Framework Core SQLite 数据库中的外键约束?
【发布时间】:2017-03-09 11:07:26
【问题描述】:

外键约束在 Entity Framework Core 中使用 SQLite 失败

我在表中有关系

[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: '外键约束失败'"}

【问题讨论】:

    标签: c# sqlite entity-framework-core


    【解决方案1】:

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

    您还可以调用 optionsBiulder.UseSqlite(connectionString, x =&gt; x.SuppressForeignKeyEnforcement()) 来防止 EF 自动打开每个连接的外键强制。

    Entity Framework Core 3 更新:

    对于 EF Core 3.0,SuppressForeignKeyEnforcement 已被移除。请参阅 docs.microsoft.com/en-us/ef/core/what-is-new/ef-core-3.0/...

    在连接字符串中使用"Foreign Keys = False"。例如。

    connectionString = "Data Source=Data.db;Password=yourpassword;Foreign Keys=False" 
    

    【讨论】:

    • 同上。谢谢布里斯拉姆。
    • 对于 EF Core 3.0 SuppressForeignKeyEnforcement 已被删除。请参阅docs.microsoft.com/en-us/ef/core/what-is-new/ef-core-3.0/… 在连接字符串中使用“Foreign Keys = False”。例如。 connectionString = "Data Source=Data.db;Password=yourpassword;Foreign Keys=False"
    猜你喜欢
    • 2018-09-28
    • 1970-01-01
    • 2017-09-07
    • 1970-01-01
    • 1970-01-01
    • 2020-11-05
    • 2019-04-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多