简体   繁体   English

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

[英]How to ignore Foreign Key Constraints in Entity Framework Core SQLite database?

Foreign Key constraint failed use SQLite with Entity Framework Core外键约束在 Entity Framework Core 中使用 SQLite 失败

I have relations in table我在表中有关系

[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);
}

I get an error from the Sqlite database:我从 Sqlite 数据库中得到一个错误:

{"SQLite Error 19: 'FOREIGN KEY constraint failed'"} {“SQLite 错误 19:'FOREIGN KEY 约束失败'”}

The PRAGMA looses effect if the connection is closed.如果连接关闭,PRAGMA 将失去作用。 You need to increase the lifetime of the connection by calling db.Database.OpenConnection() and CloseConnection() before and after.您需要通过db.Database.OpenConnection()调用db.Database.OpenConnection()CloseConnection()来增加连接的生命周期。

You can also call optionsBiulder.UseSqlite(connectionString, x => x.SuppressForeignKeyEnforcement()) to prefent EF from automatically turning foreign key enforcement on per connection.您还可以调用optionsBiulder.UseSqlite(connectionString, x => x.SuppressForeignKeyEnforcement())来防止 EF 自动打开每个连接的外键强制执行。

Entity Framework Core 3 Update:实体框架核心 3 更新:

For EF Core 3.0 SuppressForeignKeyEnforcement has been removed.对于 EF Core 3.0,SuppressForeignKeyEnforcement 已被删除。 see docs.microsoft.com/en-us/ef/core/what-is-new/ef-core-3.0/…请参阅 docs.microsoft.com/en-us/ef/core/what-is-new/ef-core-3.0/...

Use "Foreign Keys = False" in the connection string instead.在连接字符串中改用"Foreign Keys = False" Eg.例如。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM