我已修改 System.Data.SQLite 以使用最新版本的SQLite引擎,该引擎自动强制执行外键,而无需使用自定义触发器。
我也在使用SubSonic 2.x,但这将适用于任何使用 SQLite 的ORM框架,这些框架是“迟开早关”。
您如何确保在每个 SQLiteConnection.Open() 上调用语句“PRAGMA foreign_keys=true”?必须调用它,否则外键不起作用。
为了解决这个问题,我在 SQLiteConnection 类的 ConnectionString 中添加了一个“外键”属性。
外键=ON 外键=OFF
如果要使用最新版本的 SQLite,则无需修改 System.Data.SQLite,只需使用 System.Data.SQLite 的 ManagedOnly 版本,然后只需将 sqlite3.dll 替换为最新版本即可。为了启用外键支持,我只需执行一个启用外键支持的 sql 语句。例如
string databasePath = "Your database path here";
string connectionString = "Data Source=" + databasePath;
connection = new SQLiteConnection(connectionString);
connection.Open();
const string sqlString = "PRAGMA foreign_keys = ON;";
SQLiteCommand command = new SQLiteCommand(sqlString, connection);
command.ExecuteNonQuery();