我想在安装时为用户(对于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);
}
}
EntitiesContextInitializer
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
}
}
答案 0 :(得分:1)
您必须执行以下步骤才能使其正常工作:
1)使您的Configuration类成为公共类,而不是internal
(迁移配置)
2)将此代码粘贴到global.asax的application_Start:
// 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();
}
}
希望它有所帮助。