EF Code first, seeding and deployment

☆樱花仙子☆ 提交于 2019-12-13 16:22:42

问题


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
    }
}

回答1:


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.



来源:https://stackoverflow.com/questions/18017714/ef-code-first-seeding-and-deployment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!