gpt4 book ai didi

c# - EF 代码优先、播种和部署

转载 作者:太空宇宙 更新时间:2023-11-03 13:38:13 25 4
gpt4 key购买 nike

我想在安装时为我们的初始数据库添加用户(对于 ASP.NET 网络应用程序)。由于某种原因,它无法正常工作。我阅读了很多主题,其中大部分是说运行 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
}
}

最佳答案

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

1) 将您的配置类设为公共(public)类,而不是内部(迁移配置)

2) 将此代码粘贴到您的 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();
}
}

希望对您有所帮助。

关于c# - EF 代码优先、播种和部署,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18017714/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com