2011-10-06 171 views
4

我有一個簡單的sqlite數據庫與兩個表。當我手動刪除(使用SQLite Expert)表DataSets中的條目時,OneD中的相應條目將按預期刪除。當我從實體框架中刪除數據集中的條目時,它不會導致一個D中的條形碼條目被刪除。沒有產生錯誤。級聯刪除不與EF級聯

任何想法爲什麼?

問候

這裏是數據庫定義:

CREATE TABLE [DataSets] (
    [DataSetId] INTEGER NOT NULL ON CONFLICT FAIL PRIMARY KEY AUTOINCREMENT, 
    [Description] TEXT(128)); 

CREATE TABLE [OneD] (
    [OneDId] INTEGER NOT NULL ON CONFLICT FAIL PRIMARY KEY ON CONFLICT ABORT AUTOINCREMENT, 
    [DataSetId] INTEGER NOT NULL ON CONFLICT FAIL UNIQUE ON CONFLICT ABORT REFERENCES [DataSets]([DataSetId]) ON DELETE CASCADE, 
    [StockSheetLength] INTEGER NOT NULL ON CONFLICT FAIL); 

這是我如何刪除EF

 var dataSets = from ds in context.DataSets select ds; 
     foreach (var ds in dataSets) 
      context.DataSets.DeleteObject(ds); 

     context.SaveChanges(); 
     return true; 

回答

6

項從SQLite的文檔:http://www.sqlite.org/foreignkeys.html

Foreign key constraints are disabled by default (for backwards compatibility), so must be enabled separately for each database connection separately.

這可能是你的問題嗎?我不知道,如果你的實體框架與打開它默認爲:

sqlite> PRAGMA foreign_keys = ON; 

編輯:看遠一點我碰到這個偶然:http://nitoprograms.blogspot.com/2010_06_01_archive.html

The Entity Framework is actually an ADO.NET data provider that is itself wrapping an ADO.NET data provider (SQLite, to be specific). Normally, the Entity Framework will open a database connection whenever it needs one; these automatically-opened connections are automatically closed when the Entity Framework is finished with it. This default behavior works well with SQL Server due to its ADO.NET provider's connection pooling. However, it does not work well with SQLite, due to various "properties" existing on the SQLite connection itself. One example is "PRAGMA foreign_keys = ON", which enforces foreign keys only for that SQLite database connection. If the Entity Framework opens and closes its connections at will, then SQLite PRAGMAs such as these are lost.

7

這裏是我的解決這一問題:

db.Connection.StateChange += ConnectionStateChange; 

void ConnectionStateChange(object sender, System.Data.StateChangeEventArgs e) 
{ 
    if (e.CurrentState == System.Data.ConnectionState.Open) 
     db.ExecuteStoreCommand("PRAGMA foreign_keys = true;");    
} 
9

的問題可以通過在連接字符串中啓用外鍵來解決:

data source=mydb.db;foreign keys=true 
+0

當我向連接字符串添加外鍵= true時,出現此錯誤:{「底層提供程序在打開時失敗。」} –

+0

這對我來說就像一個魅力! – Shuaib