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));
context.SaveChanges();

 base.Seed(context);

}

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

   Database.SetInitializer(new SampleDbContextInitializer ());

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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