问题
When I delete a primary key with ExecuteNonQuery()
in C# from the first table it doesn't affect the second table.
But when I do the same with SQLiteStudio it does affect the second table.
Here is my SQLite code:
CREATE TABLE Zdravila(
ID INTEGER PRIMARY KEY,
NACIONALNA_SIFRA INTEGER UNIQUE NOT NULL,
IME_ZDRAVILA TEXT,
POIMENOVANJE_IZDELKA TEXT NOT NULL,
SIFRA_REZIM_IZDAJE INTEGER NOT NULL,
ATC_OZNAKA TEXT NOT NULL,
NAZIV_POTI_UPORABE TEXT NOT NULL,
FOREIGN KEY(NACIONALNA_SIFRA) REFERENCES LastnostiZdravila(NACIONALNA_SIFRA) ON DELETE CASCADE ON UPDATE CASCADE
);
CREATE TABLE LastnostiZdravila(
NACIONALNA_SIFRA INTEGER PRIMARY KEY,
NAZIV_FARMACEVTSKE_OBLIKE TEXT NOT NULL,
KOLICINA_OSNOVNE_ENOTE INTEGER NOT NULL CHECK (KOLICINA_OSNOVNE_ENOTE > 0),
OZNAKA_OSNOVNE_ENOTE TEXT NOT NULL,
PAKIRANJE TEXT NOT NULL,
SIFRA_IMETNIKA_DOVOLJENJA TEXT NOT NULL
);
PRAGMA foreign_keys = ON;
And my C# code:
SQLiteConnection conn = new SQLiteConnection(poveziZBazo);
SQLiteCommand sqlQuery = new SQLiteCommand(sql);
sqlQuery.Connection = conn;
conn.Open();
SQLiteTransaction trans;
trans = conn.BeginTransaction();
sqlQuery.CommandText = sql;
j = sqlQuery.ExecuteNonQuery();
trans.Commit();
sqlQuery.Dispose();
conn.Close();
And my Query:
"DELETE FROM LastnostiZdravila WHERE NACIONALNA_SIFRA = " + "'" + NacionalnaSifraBrisanje + "'" + ";";
(I check NacionalnaSifraBrisanje for sql commands)
回答1:
According to http://sqlite.org/pragma.html#pragma_foreign_keys:
As of SQLite version 3.6.19, the default setting for foreign key enforcement is OFF. However, that might change in a future release of SQLite.
As for now, this still defaults to false.
CL already told you that foreign_keys
setting is "per connection" - what it means is that every time you make a new connection to the SQLite database, the foreign_keys
pragma is set to default value, which is false
.
What you need to do is to execute PRAGMA foreign_keys = 1;
after every connection you make to the SQLite, so foreign keys are honored by your C# application.
This is actually what SQLiteStudio does internally and that's why it works there.
来源:https://stackoverflow.com/questions/23492758/on-delete-cascade-not-working-in-c-sharp