Code-First Development with Entity Framework 4
page 14 of 21
by Scott Guthrie
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 64625/ 140

Re-synchronizing our Model Classes with the Database

There are a couple of ways we can “re-sync” our model objects and our database:

We can manually update our database schema to match our models

We can manually delete our database file, re-run the application, and have EF automatically re-create the database

We can enable a feature of EF code-first that automatically updates our database for us whenever we change our models

Let’s look at how we can use this last automatic option with our NerdDinner application.

The RecreateDatabaseIfModelChanges Feature

CTP 4 of the EF Code First library includes a useful development-time feature that enables you to automatically re-create your database anytime you make modifications to your model classes.  When you enable it, EF identifies when any of the model classes that were used to automatically create a database are modified, and when that happens can re-create your database to match the new model class shape – without you having to take any manual steps to do so.

This capability is especially useful when you are first developing an application, since it gives you the freedom and flexibility to quickly refactor and restructure your model code however you want - without having to do any manual work to keep your database schema in sync along the way.  It works especially well with SQL CE – since it is a file-based database that can be dropped and recreated on the fly in under a second.  This can enable an incredibly fluid development workflow.

The easiest way to enable this capability is to add a Database.SetInitializer() call to the Application_Start() event handler within our Global.asax class:

This tells EF to re-create our NerdDinners.sdf database to match our NerdDinners model anytime our model classes change shape.  Now when we re-run our application we will no longer get that error message telling us that our model classes and database are out of sync.  EF will instead automatically re-create a database for us that matches our new model class shape, and our application will run fine:


View Entire Article

User Comments

No comments posted yet.

Product Spotlight
Product Spotlight 

Community Advice: ASP | SQL | XML | Regular Expressions | Windows

©Copyright 1998-2024  |  Page Processed at 2024-06-20 8:24:09 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search