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 ());