简体   繁体   English

使用SQLite和C#实施外键约束

[英]Enforce foreign key constraint with SQLite & C#

I created a foreign key constraint ON DELETE SET DEFAULT in the database and I assigned a default value. 我在数据库中创建了一个外键约束ON DELETE SET DEFAULT ,并为此分配了一个默认值。

What I tried: 我尝试了什么:

  • In App.Config: I added " foreign keys=true; " to the connectionstring. 在App.Config中:我在connectionstring中添加了“ foreign keys = true; ”。
  • I edited the dataset XSD 我编辑了数据集XSD
  • I changed the DataSet on the WinForm and enforced it there: EnforceConstraints = true 我更改了WinForm上的DataSet并在那里强制执行: EnforceConstraints = true
  • I checked, my SQLite version is high enough to support this (I use v1.0.110.0) 我检查过,我的SQLite版本足以支持这个(我使用v1.0.110.0)
  • I can't use the PRAGMA command (as shown here: Enabling Foreign key constraints in SQLite ) because the data is bound to controls. 我不能使用PRAGMA命令(如下所示: 在SQLite中启用外键约束 ),因为数据绑定到控件。
  • I rebuilt the project. 我重建了这个项目。
  • I tried it in SqliteStudio and there the constraint works but in C# it does not. 我在SqliteStudio中试过它,但约束有效,但在C#中没有。

What could I have possibly missed... 我有什么可能错过的......

Update: The App.Config was somehow desynched with the project settings thus the extra parameters were not included in the build. 更新: App.Config以某种方式与项目设置进行了同步,因此额外的参数未包含在构建中。 However adding the parameter through the project properties throws an error. 但是,通过项目属性添加参数会引发错误。

"Data Source=.\InventoryManagerDatabase.db;foreign keys=true;" 

Error: 错误:

System.InvalidOperationException: 'Unknown connection string parameter 'foreign keys'.' System.InvalidOperationException:'未知的连接字符串参数'外键'。'

Apparently this parameter does not exist? 显然这个参数不存在? I checked various resources including Enabling Foreign key constraints in SQLite & SQLite EF6 programmatically set connection string at runtime but that is weird... Did SQLite remove this parameter or rename it? 我检查了各种资源,包括在SQLiteSQLite EF6中 启用外键约束, 在运行时以编程方式设置连接字符串,但这很奇怪...... SQLite是否删除了此参数或重命名?

I also tried (as well as case-sensitivity combinations): 我也试过(以及区分大小写的组合):

EnforceFKConstraints=True;
foreign key=true;
foreign keys=true;
foreign_keys=true;
ForeignKeys=true;
Foreign Key Constraints=true;
PRAGMA foreign_keys = ON; // obviously does not work

But nothing works... 但没有任何作用......

Found it, finally! 终于找到了!

Solution: 解:

connectionString="Data Source=.\YourDatabaseName.db;Foreign Key Constraints=On;Version=3;"

Yeap they somewhere changed it to Foreign Key Constraints=On and every page on Google including StackOverflow still show the old parameter... 他们在某处将其更改为外键约束=开启并且Google上的每个页面(包括StackOverflow)仍显示旧参数...

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

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