我想在安装时为我们的初始数据库播种用户(对于 ASP.NET Web 应用程序)。由于某种原因,它无法正常工作。我已经阅读了大量主题,这些主题大多说运行update-database
在控制台上效果很好,但是这在生产环境中如何工作?
为了规避这一点,我最终得到了以下代码 - 我在这里遗漏了什么?
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);
}
}
实体上下文初始化器
internal sealed class EntitiesContextInitializer : MigrateDatabaseToLatestVersion<EMUI.Models.UsersContext, 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
}
}