Many times you want to seed data into your DB but don’t want to put all that seed data into your code files, or perhaps you want to add stored procedures, triggers or make other database changes after code first creates your database. While I would argue that the latter impacts one of the “goals” of EF Code First (i.e. centralizing your business logic in one spot), I can see where it might have value. So lets see how we can achieve this mission.
Lets start by creating our data objects. I am going to create a simple object “Tweet”:
Great now Lets wire it up to our DbContext:
You will see that my “SetInitializer” creates a special ContextInitializer. I borrowed this idea from Julie Lerman’s blog post on seeding data (http://thedatafarm.com/blog/data-access/seeding-a-database-with-ef4-code-first/). Lets take a look at the code in that guy:
As you can see we inherit from the “CreateDatabaseIfNotExists<T>” object. This means that EF Code First will only touch database schema if the database is totally dropped. Preventing any unintended accidental database modifications. In the seed method you see that I query the file system for all files that end in .sql, sort them alphabetically (so we can control the order that they are applied to our new database). Then one by one execute them against the context. Great now I can write seed files, stored procedures, triggers or whatever else I want in standard .sql files, and Code First will take care of applying them when it creates the database.
Here is an example of some .sql files for our little Twitter clone:
Nothing all that interesting, except for the naming convention. By placing the numbers in front I can control the order that they get executed against the database.
One last note, I think using EF Code First to “generate” your database for dev/test/qa environments is a great idea. This allows all development and testing to work against a “known”, “common” database state that is easily re-creatable. I am not quite sold on using it to generate the db in production. IMHO when it comes time to migrate to production you can use one of the many database schema diff tools (VS Data Dude, Red Gate, etc.) and prepare delta scripts to “Alter” the production DB to match the test/qa server, and tightly control what gets moved to production and when.