简体   繁体   中英

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.

What I tried:

  • In App.Config: I added " foreign keys=true; " to the connectionstring.
  • I edited the dataset XSD
  • I changed the DataSet on the WinForm and enforced it there: EnforceConstraints = true
  • I checked, my SQLite version is high enough to support this (I use 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.
  • I rebuilt the project.
  • I tried it in SqliteStudio and there the constraint works but in C# it does not.

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. 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'.'

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?

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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