dotnet ef迁移自动化:检测迁移的变化

时间:2023-01-19 02:15:09

I use the following CLI for DB Migrations:

我使用以下CLI进行数据库迁移:

  1. dotnet ef migrations add <Name-of-Migration>
  2. dotnet ef migrations添加 <迁移名称>
  3. dotnet ef database update
  4. dotnet ef数据库更新

However, I am looking for a way for this to happen automatically: when a change in the Model is detected.

但是,我正在寻找一种自动发生的方法:当检测到模型中的更改时。

So far, I have been able to eliminate Step 2 by doing the following in Startup.cs:

到目前为止,我已经能够通过在Startup.cs中执行以下操作来消除步骤2:

 private void SetupDatabase(IApplicationBuilder app)
    {
        using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
        {
            var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
            //Migate any pending changes:
            context.Database.Migrate();
        }
    }

This migrates any pending changes created by doing: dotnet ef migrations add <Name-of-Migration> but it does not add migration for any changes in the model. How do I automate this migrations add?

这会迁移通过执行以下操作创建的任何挂起的更改:dotnet ef迁移添加 <迁移名称> 但它不会为模型中的任何更改添加迁移。如何自动添加此迁移?

2 个解决方案

#1


11  

Updated: It is possible to move the first step of generating a migration automatically from code, a design decision that I personally do not agree with. Its still not possible in your target EF7 as I originally said (it has been removed from EF7 it seems as mentioned in this SO post as well as on this blog post by a member of Microsoft EF team mentioned in comments by Ivan), but tested in EF6 after Martin reply. The second step can be automated as you also found out already so I wont reproduce it again.

更新:可以从代码中自动生成迁移的第一步,这是我个人不同意的设计决策。它仍然不可能在你的目标EF7中,正如我最初所说的那样(它已经从EF7中移除了,似乎在这篇SO帖子中以及在Ivan评论中提到的Microsoft EF团队成员的博客文章中提到),但是已经过测试在Martin回复后的EF6中。第二步可以自动进行,因为你已经发现,所以我不会再次重现它。

The steps for the first step are as follows (in ASP.net MVC Web Application with EF6):

第一步的步骤如下(在使用EF6的ASP.net MVC Web应用程序中):

  1. In your project (which should already be running with some models and in a consistent state), go to package manager console and run Enable-Migrations –EnableAutomaticMigrations. If your application has single DB context, it has applied the changes there too.
  2. 在您的项目中(应该已经与某些模型一起运行并处于一致状态),转到程序包管理器控制台并运行Enable-Migrations -EnableAutomaticMigrations。如果您的应用程序具有单个DB上下文,则它也会在其中应用更改。
  3. Now go to an existing model and add a new field there, e.g. public String TestField { get; set; }
  4. 现在转到现有模型并在那里添加一个新字段,例如public String TestField {get;组; }
  5. As code first automatic migrations are ON, you do not need to run Add-Migration command again (hopefully, as I point out in later part of this answer), you just run Update-Database and the DB should be updated allowing your application to run fine.
  6. 当代码第一次自动迁移为ON时,您不需要再次运行Add-Migration命令(希望如我在本答案的后面部分所指出的那样),您只需运行Update-Database并且应该更新DB以允许您的应用程序运行正常。

Why automatic model change monitoring to generate and update database automatically might backfire sometimes (in my humble opinion and from MSDN page):

为什么自动模型更改监视自动生成和更新数据库可能会适得其反(在我的拙见和MSDN页面中):

  • Automatic migrations wont work in change of field renames, as per MSDN.
  • 根据MSDN,自动迁移在更改字段重命名时不起作用。
  • In case of primitive field types being added, the existing data will need to be considered and you should consider manual migrations in this scenario.
  • 如果添加了原始字段类型,则需要考虑现有数据,您应该考虑在此方案中进行手动迁移。
  • You can intersperse automatic and code-based migrations but this is not recommended in team development scenarios. If you are part of a team of developers that use source control you should either use purely automatic migrations or purely code-based migrations. Given the limitations of automatic migration MSDN recommends using code-based migrations in team environments.
  • 您可以散布自动和基于代码的迁移,但在团队开发方案中不建议这样做。如果您是使用源代码管理的开发人员团队的一员,则应使用纯粹的自动迁移或纯粹基于代码的迁移。鉴于自动迁移的限制,MSDN建议在团队环境中使用基于代码的迁移。
  • Its good to confirm that a model change is deliberate and was not a result of some leftover code while changes were being made, something that can happen and automating the complete process might slip such changes to DB.
  • 很好地确认模型更改是故意的,并且在进行更改时不是某些剩余代码的结果,可能发生的事情和自动化整个过程可能会将这些更改传递给DB。
  • The migrations that get generated are not always optimized and/or fail due to some data constraints or similar issues and hence should be reviewed.
  • 由于某些数据限制或类似问题,生成的迁移并不总是优化和/或失败,因此应进行审核。
  • Even update database has timed out for us on production data in some cases when there was loads of data the migration was handling. We had to then manually run it remotely and restart the server.
  • 在某些情况下,当迁移处理的数据量很大时,甚至更新数据库也会暂停生产数据。然后我们必须手动远程运行它并重新启动服务器。

The above might not apply to everyone, but thought should share the reason why I agree with design decision of not making the migration generation and application to DB automated.

以上内容可能并不适用于所有人,但我认为应该分享我同意设计决策的原因,即不将迁移生成和应用程序自动化生成数据库。

Everyone considering to enable automatic migrations should for sure read MSDN page for more examples and shortcomings.

考虑启用自动迁移的每个人都应该阅读MSDN页面以获取更多示例和缺点。

#2


6  

Entity Framework 4.3 has introduced the Automated Migrations.

实体框架4.3引入了自动迁移。

Although I agree with Hassan's answer stating that is might be very tricky, this option actually exists.

虽然我同意哈桑的答案,说明这可能非常棘手,但这个选项确实存在。

Here is a short resume:

这是一个简短的简历:

  1. When you enable Migrations, you must provide a parameter in the Package Manager Console:
  2. 启用迁移时,必须在程序包管理器控制台中提供参数:

enable-migrations –EnableAutomaticMigration:$true

enable-migrations -EnableAutomaticMigration:$ true

  1. A Configuration class will be automatically generated:

    将自动生成Configuration类:

    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
    
        //Set this parameter to true if you want to let auto-migration delete data when a property is removed from an entity.
        //Not setting this will result in an exception when migration should remove a column.
        AutomaticMigrationDataLossAllowed = true;
    }
    
  2. Set the DB Initializer in your Context class

    在Context类中设置DB Initializer

    Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyDBContext, MyConfigurationClass>("MyConnectionString"));
    

And there you go, change your model and see the changes...

你去,改变你的模型,看看变化......

I'm still not sure I will use it though, as I want my database to change when I say so...

我仍然不确定我会使用它,因为我希望我的数据库在我说的时候改变...

#1


11  

Updated: It is possible to move the first step of generating a migration automatically from code, a design decision that I personally do not agree with. Its still not possible in your target EF7 as I originally said (it has been removed from EF7 it seems as mentioned in this SO post as well as on this blog post by a member of Microsoft EF team mentioned in comments by Ivan), but tested in EF6 after Martin reply. The second step can be automated as you also found out already so I wont reproduce it again.

更新:可以从代码中自动生成迁移的第一步,这是我个人不同意的设计决策。它仍然不可能在你的目标EF7中,正如我最初所说的那样(它已经从EF7中移除了,似乎在这篇SO帖子中以及在Ivan评论中提到的Microsoft EF团队成员的博客文章中提到),但是已经过测试在Martin回复后的EF6中。第二步可以自动进行,因为你已经发现,所以我不会再次重现它。

The steps for the first step are as follows (in ASP.net MVC Web Application with EF6):

第一步的步骤如下(在使用EF6的ASP.net MVC Web应用程序中):

  1. In your project (which should already be running with some models and in a consistent state), go to package manager console and run Enable-Migrations –EnableAutomaticMigrations. If your application has single DB context, it has applied the changes there too.
  2. 在您的项目中(应该已经与某些模型一起运行并处于一致状态),转到程序包管理器控制台并运行Enable-Migrations -EnableAutomaticMigrations。如果您的应用程序具有单个DB上下文,则它也会在其中应用更改。
  3. Now go to an existing model and add a new field there, e.g. public String TestField { get; set; }
  4. 现在转到现有模型并在那里添加一个新字段,例如public String TestField {get;组; }
  5. As code first automatic migrations are ON, you do not need to run Add-Migration command again (hopefully, as I point out in later part of this answer), you just run Update-Database and the DB should be updated allowing your application to run fine.
  6. 当代码第一次自动迁移为ON时,您不需要再次运行Add-Migration命令(希望如我在本答案的后面部分所指出的那样),您只需运行Update-Database并且应该更新DB以允许您的应用程序运行正常。

Why automatic model change monitoring to generate and update database automatically might backfire sometimes (in my humble opinion and from MSDN page):

为什么自动模型更改监视自动生成和更新数据库可能会适得其反(在我的拙见和MSDN页面中):

  • Automatic migrations wont work in change of field renames, as per MSDN.
  • 根据MSDN,自动迁移在更改字段重命名时不起作用。
  • In case of primitive field types being added, the existing data will need to be considered and you should consider manual migrations in this scenario.
  • 如果添加了原始字段类型,则需要考虑现有数据,您应该考虑在此方案中进行手动迁移。
  • You can intersperse automatic and code-based migrations but this is not recommended in team development scenarios. If you are part of a team of developers that use source control you should either use purely automatic migrations or purely code-based migrations. Given the limitations of automatic migration MSDN recommends using code-based migrations in team environments.
  • 您可以散布自动和基于代码的迁移,但在团队开发方案中不建议这样做。如果您是使用源代码管理的开发人员团队的一员,则应使用纯粹的自动迁移或纯粹基于代码的迁移。鉴于自动迁移的限制,MSDN建议在团队环境中使用基于代码的迁移。
  • Its good to confirm that a model change is deliberate and was not a result of some leftover code while changes were being made, something that can happen and automating the complete process might slip such changes to DB.
  • 很好地确认模型更改是故意的,并且在进行更改时不是某些剩余代码的结果,可能发生的事情和自动化整个过程可能会将这些更改传递给DB。
  • The migrations that get generated are not always optimized and/or fail due to some data constraints or similar issues and hence should be reviewed.
  • 由于某些数据限制或类似问题,生成的迁移并不总是优化和/或失败,因此应进行审核。
  • Even update database has timed out for us on production data in some cases when there was loads of data the migration was handling. We had to then manually run it remotely and restart the server.
  • 在某些情况下,当迁移处理的数据量很大时,甚至更新数据库也会暂停生产数据。然后我们必须手动远程运行它并重新启动服务器。

The above might not apply to everyone, but thought should share the reason why I agree with design decision of not making the migration generation and application to DB automated.

以上内容可能并不适用于所有人,但我认为应该分享我同意设计决策的原因,即不将迁移生成和应用程序自动化生成数据库。

Everyone considering to enable automatic migrations should for sure read MSDN page for more examples and shortcomings.

考虑启用自动迁移的每个人都应该阅读MSDN页面以获取更多示例和缺点。

#2


6  

Entity Framework 4.3 has introduced the Automated Migrations.

实体框架4.3引入了自动迁移。

Although I agree with Hassan's answer stating that is might be very tricky, this option actually exists.

虽然我同意哈桑的答案,说明这可能非常棘手,但这个选项确实存在。

Here is a short resume:

这是一个简短的简历:

  1. When you enable Migrations, you must provide a parameter in the Package Manager Console:
  2. 启用迁移时,必须在程序包管理器控制台中提供参数:

enable-migrations –EnableAutomaticMigration:$true

enable-migrations -EnableAutomaticMigration:$ true

  1. A Configuration class will be automatically generated:

    将自动生成Configuration类:

    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
    
        //Set this parameter to true if you want to let auto-migration delete data when a property is removed from an entity.
        //Not setting this will result in an exception when migration should remove a column.
        AutomaticMigrationDataLossAllowed = true;
    }
    
  2. Set the DB Initializer in your Context class

    在Context类中设置DB Initializer

    Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyDBContext, MyConfigurationClass>("MyConnectionString"));
    

And there you go, change your model and see the changes...

你去,改变你的模型,看看变化......

I'm still not sure I will use it though, as I want my database to change when I say so...

我仍然不确定我会使用它,因为我希望我的数据库在我说的时候改变...