简体   繁体   English

控制EF数据库的创建和迁移

[英]Controling EF database creation and migration

I have an application using a EF model for the database. 我有一个使用EF模型的数据库应用程序。 This application is going to run on multiple computers in the same network using one database. 该应用程序将使用一个数据库在同一网络中的多台计算机上运行。 To make sure this works ok when there are updates. 为确保有更新时此方法正常。 I want to control the migration and installation of the database. 我想控制数据库的迁移和安装。

I thought I could disable the EF initializer and in my application startup checks using context.database.Exists() and context.database.CompatibleWithModel if the application matches the database. 我以为可以禁用EF初始化程序,并在应用程序启动时使用context.database.Exists()context.database.CompatibleWithModel进行检查如果应用程序与数据库匹配)。 If this is not the case I want to create it after I check if all client are offline. 如果不是这种情况,我想在检查所有客户端是否都脱机之后创建它。

But my problem is when I run context.database.create() , I get an error 但是我的问题是当我运行context.database.create()时 ,出现错误

{"Unable to update database to match the current model because there are pending changes and automatic migration is disabled. Either write the pending model changes to a code-based migration or enable automatic migration. Set DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable automatic migration."} {“由于存在暂挂更改,并且禁用了自动迁移,因此无法更新数据库以匹配当前模型。要么将暂挂模型更改写入基于代码的迁移,要么启用自动迁移。将DbMigrationsConfiguration.AutomaticMigrationsEnabled设置为true即可启用自动迁移。 “}

What is the best approach to controlling the creation of the DB and migrates from code? 控制数据库创建并从代码迁移的最佳方法是什么? And not from the initializer. 而不是来自初始化程序。

The problem you've got seems not related to db creation. 您遇到的问题似乎与数据库创建无关。 Your model just simply does not comply any more with what migrations states. 您的模型只是完全不符合迁移说明。 Just run add-migration script to regenerate migration files and everything should work fine. 只需运行add-migration脚本来重新生成迁移文件,一切就可以正常工作。 If you would like to allow automatic migrations (not required to regenerate migration classes after model changes - but generaly this is a bad idea) just set AutomaticMigrationsEnabled = true in Configuration class for migrations and this will as well fix your error. 如果您希望允许自动迁移(在模型更改后不需要重新生成迁移类-但通常这是一个坏主意),只需在Configuration类中为迁移设置AutomaticMigrationsEnabled = true,这样就可以修复您的错误。 To control migrations from code the best thing you could use is DbMigrator. 要控制从代码的迁移,您最好使用DbMigrator。 You use it like that: 您可以这样使用它:

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

With the Update method you can define to which migration you want to migrate your db. 使用Update方法,您可以定义要将数据库迁移到哪个迁移。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM