Tony Vitabile
Tony Vitabile

Reputation: 8614

Adding code to Entity Framework 6 model that runs whenever a new model context is instantiated

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?

Upvotes: 0

Views: 894

Answers (1)

Panagiotis Kanavos
Panagiotis Kanavos

Reputation: 131730

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;");            
}

Upvotes: 1

Related Questions