Reputation: 10648
I am using ASP.NET MVC 4 Internet application template. I have successfully added some custom tables to the existing database that is created automatically but now I want to seed some data to one of my tables once database is created. I know I can do it by overriding the Seed method on the database initializer but as by default asp.net mvc4 sets the initializar to null I am not sure if I change the initializer can cause some new issues or side effects... how to do it?
// I could implement this custom initializer but as by default is set to null
//
public class UsersContextSeedInitializer : CreateDatabaseIfNotExists<UsersContext>
{
protected override void Seed(UsersContext context)
{
// Populate my table here
}
}
private class SimpleMembershipInitializer
{
public SimpleMembershipInitializer()
{
Database.SetInitializer<UsersContext>(null);
// I could do it here or better below?: Database.SetInitializer(new UsersContextSeedInitializer());
try
{
using (var context = new UsersContext())
{
if (!context.Database.Exists())
{
// Create the SimpleMembership database without Entity Framework migration schema
((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
}
}
// better here?: Database.SetInitializer(new UsersContextSeedInitializer());
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
}
catch (Exception ex)
{
throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
}
}
}
Upvotes: 0
Views: 837
Reputation: 3012
You should call the database initializer from your Global.asax as it needs to be called before the first use of the DbContext.
In John Papa's pluralsight course on SPA, the implementation he has is as follows, this is in his derived DbContext Class (note the comment):
// ToDo: Move Initializer to Global.asax; don't want dependence on SampleData
static CodeCamperDbContext()
{
Database.SetInitializer(new CodeCamperDatabaseInitializer());
}
This question also supports this.
Upvotes: 1