2

我想在安装时为我们的初始数据库播种用户(对于 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
    }
}
4

1 回答 1

1

您必须执行以下步骤才能使其正常工作:

1)使您的配置类公开,而不是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();
    }
}

希望能帮助到你。

于 2013-08-02T13:16:45.173 回答