I have got a guess(suddenly!!!) of how to make FK work in the demonstrated sample. And I have tried it immediately. And WOW, it works for me with latest Dapper/SQLite.
Of course, I have completed the original project many years ago, but I believe the clear description of the original behavior can be helpful to someone in future.
The reason for non-working constraints is that fact that Dapper preserve connection's state and flags when executing queries. So, when the connection is initially closed, as in original sample, it will be opened again before command execution and then closed after completion. And any pragmas will be lost.
If you make the connection open via the c.Open()
all the settings will be preserved between command executions (and that is why all the things works for @CL in console). So this is the first and the simplest solution:
using(SQLiteConnection c = new SQLiteConnection("Data Source=" + db).OpenAndReturn()) {
// ... commands
}
As an alternatives for closed connection, you should either add "PRAGMA foreign_keys = ON;" statement into each query:
c.Execute("PRAGMA foreign_keys = ON; INSERT INTO Departments_treePath (ancestor,descendant) VALUES (7,7)");
or enforce the FK constraints at the connection level:
SQLiteConnection c = new SQLiteConnection("Data Source=" + db + ";foreign keys=true;")