.net 在生产中使用实体框架(代码优先)迁移

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10848746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 16:27:06  来源:igfitidea点击:

Using Entity Framework (code first) migrations in production

.netentity-frameworkef-code-firstef-migrations

提问by devdigital

I'm just looking into using EF migrations for our project, and in particular for performing schema changes in production between releases.

我只是考虑在我们的项目中使用 EF 迁移,特别是在版本之间的生产中执行架构更改。

I have seen mentioned that there is an API to perform these migrations at run-time using the DbMigrationclass, but I can't find any specific examples.

我已经看到提到有一个 API 可以在运行时使用DbMigration该类执行这些迁移,但我找不到任何具体示例。

Ideally, I would want one DbMigrationfile for every database change, and for those changes to be applied automatically on application start up from the current version up to the latest version.

理想情况下,我希望DbMigration每个数据库更改都有一个文件,并且这些更改在从当前版本到最新版本的应用程序启动时自动应用。

回答by WDRust

There is a Database Initializer you can use to achieve the migration to latest version on startup (or better, the dbinitializer will kick in on first db access), the MigrateDatabaseToLatestVersion, you use it like that:

有一个 Database Initializer 可用于在启动时迁移到最新版本(或者更好的是,dbinitializer 将在第一次访问数据库时启动)MigrateDatabaseToLatestVersion,您可以像这样使用它:

Database.SetInitializer<ObjectContext>(
    new MigrateDatabaseToLatestVersion<ObjectContext, Configuration>());

Regarding having one file per migration, if you enable automatic migrations you will find them in the Migrationsfolder (by default) in the root of your project.

关于每个迁移有一个文件,如果您启用自动迁移,您将在Migrations项目根目录的文件夹中(默认情况下)找到它们。

Relevant info, with examples, here: http://weblogs.asp.net/fredriknormen/archive/2012/02/15/using-entity-framework-4-3-database-migration-for-any-project.aspx

相关信息,包括例子,这里:http: //weblogs.asp.net/fredriknormen/archive/2012/02/15/using-entity-framework-4-3-database-migration-for-any-project.aspx

回答by mackie

This works too:

这也有效:

var configuration = new MyDbContextConfiguration();
configuration.TargetDatabase = new DbConnectionInfo(
    database.ConnectionString, database.ProviderName);

var migrator = new DbMigrator(configuration);
migrator.Update();

You can also call:

您也可以拨打:

migrator.GetPendingMigrations();

to get a list of the migrations it needs to apply.

获取需要应用的迁移列表。

回答by Worthy7

Since you didn't specify which Visual Studio version you are using, or Database, I will add an answer here to say that in VS2015 with Microsoft's SQL Server, this is now incredibly easy using the "Publish" tool.

由于您没有指定您使用的是哪个 Visual Studio 版本或数据库,我将在此处添加一个答案,说明在使用 Microsoft SQL Server 的 VS2015 中,现在使用“发布”工具非常容易。

You do not need to bother with the API you speak of. Simply do your work locally, changing your models, applying migrations etc, then when you want to push out to release/test servers, use the publish tool.

您无需为您所说的 API 烦恼。只需在本地完成您的工作、更改模型、应用迁移等,然后当您想要推送到发布/测试服务器时,请使用发布工具。

You can select to apply any migrations you have made locally, to the remote server the first time the application is started up.

您可以选择在第一次启动应用程序时将您在本地进行的任何迁移应用到远程服务器。

Once you have all of your migrations and everything done locally (presumable in your Dev env) then you publish (right click the project, click "Publish..." Tick the "Execute Code First Migrations (runs on application startup)" checkbox under the "Settings" tab and then it will apply the migrations the first time the app is accessed (so there will be a short delay the first time).

一旦您完成了所有迁移并在本地完成了所有操作(可能在您的开发环境中),然后您发布(右键单击项目,单击“发布...” “设置”选项卡,然后它将在第一次访问应用程序时应用迁移(因此第一次会有短暂的延迟)。

Publish Web using Web-Deploy

使用 Web-Deploy 发布 Web

Guide: https://msdn.microsoft.com/en-us/library/dd465337(v=vs.110).aspx

指南:https: //msdn.microsoft.com/en-us/library/dd465337(v=vs.110).aspx

I learned all this because I had to do this to a Windows 2012 server: http://www.sherweb.com/blog/how-to-install-webdeploy-on-windows-server-2012/

我学到了这一切,因为我必须对 Windows 2012 服务器执行此操作:http: //www.sherweb.com/blog/how-to-install-webdeploy-on-windows-server-2012/

Good luck!

祝你好运!

回答by Panos Roditakis

I wanted to control which migrations run explicitly in code and after a lot of search i managed to develop the following technique without the need of a DbConfiguration class or automatic migrations enabled:

我想控制在代码中显式运行哪些迁移,经过大量搜索,我设法开发了以下技术,而无需启用 DbConfiguration 类或自动迁移:

public static void RunMigration(this DbContext context, DbMigration migration)
{            
    var prop = migration.GetType().GetProperty("Operations", BindingFlags.NonPublic | BindingFlags.Instance);
    if (prop != null)
    {
        IEnumerable<MigrationOperation> operations = prop.GetValue(migration) as IEnumerable<MigrationOperation>;
        var generator = new SqlServerMigrationSqlGenerator();
        var statements = generator.Generate(operations, "2008");
        foreach (MigrationStatement item in statements)
            context.Database.ExecuteSqlCommand(item.Sql);
    }
}

And if we had a migration like this:

如果我们有这样的迁移:

public class CreateIndexOnContactCodeMigration : DbMigration
{
    public override void Up()
    {
        this.CreateIndex("Contacts", "Code");
    }

    public override void Down()
    {
        base.Down();
        this.DropIndex("Contacts", "Code");
    }
}

We would use it like that:

我们会这样使用它:

using (var dbCrm = new CrmDbContext(connectionString))
{
    var migration = new CreateIndexOnContactCodeMigration();
    migration.Up();                
    dbCrm.RunMigration(migration);
}

Regards.

问候。

回答by LuTheZy

To add to all the answers already posted. Entity Framework uses a table: dbo.__MigrationHistory to keep track of all the migrations that have already been applied to the database to avoid running a migration that for example: inserts data or changes the database schema.

添加到已发布的所有答案中。实体框架使用一个表:dbo.__MigrationHistory 来跟踪已应用于数据库的所有迁移,以避免运行迁移,例如:插入数据或更改数据库架构。

If you wish to run a script such as run adding data or changing the schema of the database you can create an empty migration using Package Manager Console and run the script via the the newly added migration. Ensure you use the initializer is used to prevent EF from dropping and recreating the database on every run.

如果您希望运行脚本,例如运行添加数据或更改数据库的架构,您可以使用包管理器控制台创建一个空迁移,并通过新添加的迁移运行脚本。确保您使用初始化程序来防止 EF 在每次运行时删除和重新创建数据库。

     public override void Up()
    {
        string directoryToSearchScripts = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..\..\"));

        string scriptFilePath = Directory.GetFiles(directoryToSearchScripts, "dummy-script.sql", SearchOption.AllDirectories).FirstOrDefault();
        if (!string.IsNullOrEmpty(scriptFilePath))
        {
            string fundsSqlScript = File.ReadAllText(scriptFilePath);
            Sql(fundsSqlScript);
        }
    }

    public override void Down()
    {
    }

When you publish the application and check the "Execute Code First Migrations" option, EF will run the migrations that have not yet been applied to the database.

当您发布应用程序并选中“执行代码优先迁移”选项时,EF 将运行尚未应用于数据库的迁移。