2014-09-22

Entity Framework on system databases

Entity Framework supports code only entity models. The default behavior is to deploy this model to the connected database. If you want to access system databases this is unacceptable. Fortunately this can be disabled. Unfortunately it's not easy. You have to implement an custom database initialization strategy. The following example is adding an check if the code model is compatible with the current database.

private class DatabaseInitializer : IDatabaseInitializer<SqlServerCatalog>
{

    public void InitializeDatabase(SqlServerCatalog context)
    {
        if (!context.Database.CompatibleWithModel(false))
            throw new Exception("");
    }
}

Now you habe to override the static constructor of your implementation of the DbContext class:

static YourDBContext()
{
    System.Data.Entity.Database.SetInitializer<YourDBContext>(new DatabaseInitializer());
}

No comments: