One of the things you might have noticed in
the above screen-shot is that we lost our dinner data when we recreated the database.
This is because the automatic “RecreateDatabaseIfModelChanges” behavior isn’t
intended for production scenarios where you want to “migrate” existing data
from one schema to another. Instead it is designed for development
scenarios where you want the database to be quickly and automatically updated
for you – without you having to take any manual steps or specify migration
rules to do so.
Note: We are separately working to provide
better data migration support for scenarios where you are working with
production data and want to version the schema. We think of that as a
different scenario than this early development-time feature that I’m describing
here. The data migration capability isn’t enabled yet with this week’s
CTP.
EF supports the ability for us to optionally
“seed” our generated database with default/test data anytime the database is
created/recreated. I find this feature really useful since it enables me
to refactor a model, and then quickly run the application to try out a scenario
– without having to enter in a bunch of test data manually to do so.
We can “seed” our NerdDinners database with
default data by writing a “NerdDinnersIntializer” class like below. I’m
using it to create two “sample dinners” and adding them to our database like
so:
We can then update the Database.Initializer() call we added
to our Global.asax to use this “NerdDinnersInitializer” class at startup:
And now anytime we make a change to one of our NerdDinner
model classes, the database will be automatically dropped and recreated to
match our models, and we’ll have two dinners already seeded in the database for
testing purposes:
Easy Refactoring
The above features make it really easy to evolve and
refactor your code at development time – without having to use tools or run
scripts to manually keep your database in sync with your code changes.
Because our model classes, LINQ expressions, and “seed” test
data are all strongly typed, we can also take advantage of refactoring tool
support inside Visual Studio to quickly and automatically apply changes across
our code base in a quick and easy way.