I want to seed our initial database with users (for a ASP.NET web app) on install. For some reason its not working correctly. Ive read loads of topics that mostly say run update-database
which works great from the console but how does this work in a production environment?
As an attempt to circumvent this I have ended up with the following code - what am I missing here?
Global.asax.cs::Application_Start()
try
{
initializationError = null;
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
}
catch (Exception ex)
{
initializationError = ex;
}
// Initialize database and seed data
Database.SetInitializer(new EntitiesContextInitializer());
// Now initialize it
using (var context = new EMUI.Models.UsersContext())
{
if (!context.Database.Exists())
{
context.Database.Initialize(true);
}
}
EntitiesContextInitializer
internal sealed class EntitiesContextInitializer : MigrateDatabaseToLatestVersion<EMUI.Models.UsersContext, Configuration>
{
}
Configuration
internal sealed class Configuration : DbMigrationsConfiguration<EMUI.Models.UsersContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(EM.Models.UsersContext context)
{
if (!WebSecurity.Initialized)
{
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
}
if (!Roles.RoleExists("Administrator"))
{
Roles.CreateRole("Administrator");
}
// More similar seeding
}
}
You have to do the following steps to make it works:
1) make your Configuration class as a public, not internal
(Configuration of migrations)
2) paste this code to your application_Start of global.asax:
// Now initialize it
using (var context = new EMUI.Models.UsersContext())
{
if (!context.Database.Exists())
{
Configuration configuration = new Configuration();
configuration.ContextType = typeof(EMUI.Models.UsersContext);
var migrator = new DbMigrator(configuration);
migrator.Update();
}
}
Hope it helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.