Seed your database with test data using the entity framework

Recently I’ve started to use Entity Framework Code First in favor of linq2sql. The main reason to choose Entity framework is it’s more advanced feature set, and especially cool upcoming features like data migrations. In this post we fill focus on Data Initializers for EF Code First, this feature allows you to seed your database in development scenario’s with some standard data for testing purposes. In this post I’m assuming you’ll already have some experience using EF Code First

Especially useful in case you work in teams, I mean who hasn’t been in the situation where you spend several hours tracking down this extremely annoying bug just to find out that there was an error in the test data. Making the seeding your database part of your development strategy unfortunately doesn’t eliminate the problem, but reduces the risk of such problems greatly.

To be more concrete how do we start using this cool feature?

First of all you’ll need to get the latest version of the entity framework (this post was written for entity framework version 4.2) either by using nuget or by downloading it manually.

For the next step I assume that you are using mvc, but this could as well apply to webforms, or windows forms applications. Adding the below line to your Application_Start() event in Global.asax will execute the database operations you’ll define in the MyDataContextDbInitializer class which we’ll create in the next step.

protected void Application_Start()
    System.Data.Entity.Database.SetInitializer(new MyDataContextDbInitializer());

Creating a database initializer can be done by inheriting from either of those generic classes:


The first as you can read from the class name recreates the database only in case your entities (model classes) have changed, the later always executes the database initialization code. Always recreating the database is useful in case you just started to define your entities, when you are done doing that, you can switch to DropCreateDatabaseIfModelChanges for faster run times during development.

To actually start to implement the class we have to override the Seed method as following:

public class MyDataContextDbInitializer : DropCreateDatabaseIfModelChanges<MyDataContext>
   protected override void Seed(MagazineContext context)
     context.Customers.Add(new Customer() { CustomerName = "Test Customer" });

As you can see you’ll be provided with an instance of your data context class, and can start to add data for your entities. You don’t have to call context.SaveChanges(); as this is done by the base class.

That’s all for now later i’ll post some more tips and tricks on how to get most out of database initializers.

Leave a Comment