0

I'm using EF6 and the latest build of the SQLite EF6 provider. There's a PRAGMA statement that I need to be executed whenever a new model context is instantiated and the connection opened.

Does EF6 have some mechanism that allows me to do this? Or am I going to be modifying my code everywhere that the model is used to check the PRAGMA and set it to the desired value? Note that there is no connection string property that corresponds to this PRAGMA or I'd do it there.

EDIT In the interests of completeness, this is not a code-first model. It's a database first model. I know that the context class is a partial. Could add a custom constructor in a partial file for the context and then I just need to call it instead of the default constructor?

Tony Vitabile
  • 8,298
  • 15
  • 67
  • 123

1 Answers1

1

The actual problem is that you need to run a PRAGMA each time a connection is opened, not when a context is created. A PRAGMA statement or any SQL statement can only be executed after a connection opens. This happens when you explicitly call Open or implicitly when you save changes.

You can attach an event handler to the Connection.StateChange event, as shown in this SO question:

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;");            
}
Community
  • 1
  • 1
Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
  • This looks promising. Where would this code go? Can it go into a partial file for the entity model? I've worked with EF 4 in the past but I'm very new to EF6 and I'm not familiar with the differences between the two. – Tony Vitabile Dec 23 '14 at 16:31
  • You can add a custom constructor in a partial file and call this instead of one of the default constructors, taking care to invoke the default constructor with a `:base()` statement – Panagiotis Kanavos Dec 23 '14 at 16:35
  • Could the answer be updated with details on where to put this code, as discussed in these comments? – deed02392 Jul 24 '15 at 11:21