2011-05-01 23 views
1

SQLite的foreignkeys我明白了,只有這樣才能使FK約束SQLite是打開這個編譯:使在NHibernate的

PRAGMA foreign_keys = ON; 

但不幸的是,如果我理解正確的話,我將不得不執行該在每個會話開始時進行查詢。我對麼? 我怎樣才能「自動」與NHibernate?有沒有辦法掛鉤NH,並在開幕後立即執行? 我使用NH 3.0。

回答

7

好的我找到了適合我的答案。學分轉到詹姆斯·科瓦奇(similar question

我已經創建了自己的驅動程序基於SQLite20Driver和重載創建連接方法(代碼爲James' GitHub

public override IDbConnection CreateConnection() 
    { 
     DbConnection connection = (DbConnection)base.CreateConnection(); 
     connection.StateChange += Connection_StateChange; 
     return connection; 
    } 

    private static void Connection_StateChange(object sender, StateChangeEventArgs e) 
    { 
     if ((e.OriginalState == ConnectionState.Broken || e.OriginalState == ConnectionState.Closed || e.OriginalState == ConnectionState.Connecting) && 
      e.CurrentState == ConnectionState.Open) 
     { 
      DbConnection connection = (DbConnection)sender; 
      using (DbCommand command = connection.CreateCommand()) 
      { 
       // Activated foreign keys if supported by SQLite. Unknown pragmas are ignored. 
       command.CommandText = "PRAGMA foreign_keys = ON"; 
       command.ExecuteNonQuery(); 
      } 
     } 
    } 

就像一個魅力:)。

+0

你可以接受你自己的答案。你可能應該。 – 2011-05-01 22:52:14

+0

是的,我應該,而且我會在兩天內,當stackoverflow將允許我:)。 – ppiotrowicz 2011-05-02 12:50:51