For some reason I cannot get my application to seed the database with some test data when the application starts up.
Order of execution:
1) Application_Start() in Global.asax
- Database.SetInitializer<LocatorContext>(new DropCreateDatabaseAlways<LocatorContext>());
- new LocatorContext.DropCreateIfChangeInitializer()
.InitializeDatabase(new LocatorContext());
2) onModelCreating() in my DBContext class
3) Page is rendered and no data is inserted into the database
Any thoughts as to why or how I can fix it would be much appreciated.
My Global.asax.cs File
//Global.asax.cs
protected void Application_Start()
{
Database.SetInitializer<LocatorContext>(new DropCreateDatabaseAlways<LocatorContext>());
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
My DBContext Class
//ClubLocatorContext.cs
using System;
using System.Collections.Generic;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using ClubLocator.Models;
using ClubLocator.Models.ViewModels;
namespace ClubLocator.DAL
{
public class LocatorContext : DbContext
{
public DbSet<Prospect> Prospects { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
public void Seed(LocatorContext context)
{
var prospect = new List<Prospect>
{
new Prospect
{
FirstName = "John",
LastName = "Smith",
Address1 = "1313 Mockingbird Lane",
Email = "jsmith@example.com"
}
};
prospect.ForEach(r => context.Prospects.Add(r));
context.SaveChanges();
}
public class DropCreateIfChangeInitializer : DropCreateDatabaseIfModelChanges<LocatorContext>
{
protected override void Seed(LocatorContext context)
{
context.Seed(context);
base.Seed(context);
}
}
public class CreateInitializer : DropCreateDatabaseAlways<LocatorContext>
{
protected override void Seed(LocatorContext context)
{
context.Seed(context);
base.Seed(context);
}
}
static LocatorContext()
{
#if DEBUG
Database.SetInitializer<LocatorContext> (new DropCreateIfChangeInitializer ());
#else
Database.SetInitializer<LocatorContext> (new CreateInitializer ());
#endif
}
}
}