Add test data in MVC for development

Sometimes it is easy to using sample data for MVC development.  Overriding Seed method and re-initializing database will save time for developer comparing with executing Code-First migration. Three steps can achieve the goal.

  1. Create a class “SampleDbContextInitializer” inheriting from  DropCreateDatabaseAlways<SampleDbContext>
  2. Override method Seed. e.g.

protected override void Seed(SampleDbContext context)

var addresses = new List<Address>
new Address() { …},
new Address() { …},
addresses.ForEach(a => context.Addresses.Add(a));



3. Add SampleDbContextInitializer to method Application_Start() in Global.asax.cs

   Database.SetInitializer(new SampleDbContextInitializer ());


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s