Force Database Initialization in Code First EF

Continuing on the previous post about using the drop-in Altairis.Web.Security membership provider, I ran into an issue where the database may not be recreated in a timely fashion on a change to the model classes. For example if you add the following property to the User class:

public string FullName { get; set; }

And change the initializer in the ApplicationDB.cs class to drop and create the database on model change:

public class DBInitializer : DropCreateDatabaseIfModelChanges<ApplicationDB> 

The problem is if you then access the database by creating a new user in the “Account/Register” controller, the database will not drop and create because the Altairis membership provider uses non-EF (ADO.Net classic) methods of data access. Therefore, the Entity Framework access methods haven’t been touched yet and won’t drop/create the DB until that time.

The solution is to add a section to the Application_Start() method in the Global.asax:

protected void Application_Start() {
     AreaRegistration.RegisterAllAreas();

     // Initializes and seeds the database.
     Database.SetInitializer(new DBInitializer());

     // Forces initialization of database on model changes.
     using (var context = new ApplicationDB()) {
          context.Database.Initialize(force: true);
     }

     RegisterGlobalFilters(GlobalFilters.Filters);
     RegisterRoutes(RouteTable.Routes);
}

The code in lines 8-10 forces the context to initialize the database and if there is a model change then it will drop and recreate the database on start of the application, before it can be accessed by the non-EF methods.

The example ASP.Net MVC3 application has been updated with these changes and is available for download at Github: Download Code


3 thoughts on “Force Database Initialization in Code First EF”

Commenter
Ciwan
December 1, 2011 at 7:26 am

Hello James
I have followed your steps from Previous related post and this one, but it isn’t working for me. I am getting the following error.
Can you please help me resolve the error ? :( I would greatly appreciate it.
Thank You.


Commenter
James Culbertson
December 1, 2011 at 8:28 am

Hi Ciwan,
I responded to the post that you linked with some suggestions as it looks like a possible DB permissions problem.
-James


Commenter
Dan
November 29, 2012 at 11:23 pm

Thanks James, this was a great help.