.net 如何为多个上下文启用 EF 迁移到单独的数据库?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13469881/
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
How do I enable EF migrations for multiple contexts to separate databases?
提问by aknuds1
How do I enable Entity Framework 5 (version 5.0.0) migrations for multiple DB contexts in the same project, where each context corresponds to its own database? When I run Enable-Migrationsin the PM console (Visual Studio 2012), there's an error because of there being multiple contexts:
如何为同一项目中的多个数据库上下文启用实体框架 5(版本 5.0.0)迁移,其中每个上下文对应于自己的数据库?当我Enable-Migrations在 PM 控制台(Visual Studio 2012)中运行时,由于存在多个上下文而出现错误:
PM> Enable-Migrations
More than one context type was found in the assembly 'DatabaseService'.
To enable migrations for DatabaseService.Models.Product1DbContext, use Enable-Migrations -ContextTypeName DatabaseService.Models.Product1DbContext.
To enable migrations for DatabaseService.Models.Product2DbContext, use Enable-Migrations -ContextTypeName DatabaseService.Models.Product2DbContext.
If I run Enable-Migrations -ContextTypeName DatabaseService.Models.Product1DbContextI'm not allowed to run Enable-Migrations -ContextTypeName DatabaseService.Models.Product2DbContextbecause a migration already exists: Migrations have already been enabled in project 'DatabaseService'. To overwrite the existing migrations configuration, use the -Force parameter.
如果我运行,则Enable-Migrations -ContextTypeName DatabaseService.Models.Product1DbContext不允许运行,Enable-Migrations -ContextTypeName DatabaseService.Models.Product2DbContext因为迁移已经存在:Migrations have already been enabled in project 'DatabaseService'. To overwrite the existing migrations configuration, use the -Force parameter.
回答by ckal
The 2nd call to Enable-Migrations is failing because the Configuration.cs file already exists. If you rename that class and file, you should be able to run that 2nd Enable-Migrations, which will create another Configuration.cs.
对 Enable-Migrations 的第二次调用失败,因为 Configuration.cs 文件已存在。如果您重命名该类和文件,您应该能够运行第二个 Enable-Migrations,这将创建另一个 Configuration.cs。
You will then need to specify which configuration you want to use when updating the databases.
然后,您需要指定更新数据库时要使用的配置。
Update-Database -ConfigurationTypeName MyRenamedConfiguration
回答by Eric J.
In addition to what @ckal suggested, it is criticalto give each renamed Configuration.cs its own namespace. If you do not, EF will attempt to apply migrations to the wrong context.
除了@ckal 的建议之外,为每个重命名的 Configuration.cs 提供自己的命名空间也很重要。如果不这样做,EF 将尝试将迁移应用于错误的上下文。
Here are the specific steps that work well for me.
以下是对我来说效果很好的具体步骤。
If Migrations are messed up and you want to create a new "baseline":
如果迁移搞砸了并且您想创建一个新的“基线”:
- Delete any existing .cs files in the Migrations folder
- In SSMS, delete the __MigrationHistory system table.
- 删除 Migrations 文件夹中的所有现有 .cs 文件
- 在 SSMS 中,删除 __MigrationHistory 系统表。
Creating the initial migration:
创建初始迁移:
In Package Manager Console:
Enable-Migrations -EnableAutomaticMigrations -ContextTypeName NamespaceOfContext.ContextA -ProjectName ProjectContextIsInIfNotMainOne -StartupProjectName NameOfMainProject -ConnectionStringName ContextAIn Solution Explorer: Rename Migrations.Configuration.cs to Migrations.ConfigurationA.cs. This should automatically rename the constructor if using Visual Studio. Make sure it does. Edit ConfigurationA.cs: Change the namespace to NamespaceOfContext.Migrations.MigrationsA
Enable-Migrations -EnableAutomaticMigrations -ContextTypeName NamespaceOfContext.ContextB -ProjectName ProjectContextIsInIfNotMainOne -StartupProjectName NameOfMainProject -ConnectionStringName ContextBIn Solution Explorer: Rename Migrations.Configuration.cs to Migrations.ConfigurationB.cs. Again, make sure the constructor is also renamed appropriately. Edit ConfigurationB.cs: Change the namespace to NamespaceOfContext.Migrations.MigrationsB
add-migration InitialBSchema -IgnoreChanges -ConfigurationTypeName ConfigurationB -ProjectName ProjectContextIsInIfNotMainOne -StartupProjectName NameOfMainProject -ConnectionStringName ContextBUpdate-Database -ConfigurationTypeName ConfigurationB -ProjectName ProjectContextIsInIfNotMainOne -StartupProjectName NameOfMainProject -ConnectionStringName ContextBadd-migration InitialSurveySchema -IgnoreChanges -ConfigurationTypeName ConfigurationA -ProjectName ProjectContextIsInIfNotMainOne -StartupProjectName NameOfMainProject -ConnectionStringName ContextAUpdate-Database -ConfigurationTypeName ConfigurationA -ProjectName ProjectContextIsInIfNotMainOne -StartupProjectName NameOfMainProject -ConnectionStringName ContextA
在包管理器控制台中:
Enable-Migrations -EnableAutomaticMigrations -ContextTypeName NamespaceOfContext.ContextA -ProjectName ProjectContextIsInIfNotMainOne -StartupProjectName NameOfMainProject -ConnectionStringName ContextA在解决方案资源管理器中:将 Migrations.Configuration.cs 重命名为 Migrations.ConfigurationA.cs。如果使用 Visual Studio,这应该会自动重命名构造函数。确保它确实如此。编辑 ConfigurationA.cs:将命名空间更改为 NamespaceOfContext.Migrations.MigrationsA
Enable-Migrations -EnableAutomaticMigrations -ContextTypeName NamespaceOfContext.ContextB -ProjectName ProjectContextIsInIfNotMainOne -StartupProjectName NameOfMainProject -ConnectionStringName ContextB在解决方案资源管理器中:将 Migrations.Configuration.cs 重命名为 Migrations.ConfigurationB.cs。同样,确保构造函数也被适当地重命名。编辑 ConfigurationB.cs:将命名空间更改为 NamespaceOfContext.Migrations.MigrationsB
add-migration InitialBSchema -IgnoreChanges -ConfigurationTypeName ConfigurationB -ProjectName ProjectContextIsInIfNotMainOne -StartupProjectName NameOfMainProject -ConnectionStringName ContextBUpdate-Database -ConfigurationTypeName ConfigurationB -ProjectName ProjectContextIsInIfNotMainOne -StartupProjectName NameOfMainProject -ConnectionStringName ContextBadd-migration InitialSurveySchema -IgnoreChanges -ConfigurationTypeName ConfigurationA -ProjectName ProjectContextIsInIfNotMainOne -StartupProjectName NameOfMainProject -ConnectionStringName ContextAUpdate-Database -ConfigurationTypeName ConfigurationA -ProjectName ProjectContextIsInIfNotMainOne -StartupProjectName NameOfMainProject -ConnectionStringName ContextA
Steps to create migration scripts in Package Manager Console:
在包管理器控制台中创建迁移脚本的步骤:
Run command
Add-Migration MYMIGRATION -ConfigurationTypeName ConfigurationA -ProjectName ProjectContextIsInIfNotMainOne -StartupProjectName NameOfMainProject -ConnectionStringName ContextAor -
Add-Migration MYMIGRATION -ConfigurationTypeName ConfigurationB -ProjectName ProjectContextIsInIfNotMainOne -StartupProjectName NameOfMainProject -ConnectionStringName ContextBIt is OK to re-run this command until changes are applied to the DB.
Either run the scripts against the desired local database, or run Update-Database without -Script to apply locally:
Update-Database -ConfigurationTypeName ConfigurationA -ProjectName ProjectContextIsInIfNotMainOne -StartupProjectName NameOfMainProject -ConnectionStringName ContextAor -
Update-Database -ConfigurationTypeName ConfigurationB -ProjectName ProjectContextIsInIfNotMainOne -StartupProjectName NameOfMainProject -ConnectionStringName ContextB
运行命令
Add-Migration MYMIGRATION -ConfigurationTypeName ConfigurationA -ProjectName ProjectContextIsInIfNotMainOne -StartupProjectName NameOfMainProject -ConnectionStringName ContextA或者 -
Add-Migration MYMIGRATION -ConfigurationTypeName ConfigurationB -ProjectName ProjectContextIsInIfNotMainOne -StartupProjectName NameOfMainProject -ConnectionStringName ContextB在更改应用于 DB 之前,可以重新运行此命令。
要么针对所需的本地数据库运行脚本,要么运行不带 -Script 的 Update-Database 以在本地应用:
Update-Database -ConfigurationTypeName ConfigurationA -ProjectName ProjectContextIsInIfNotMainOne -StartupProjectName NameOfMainProject -ConnectionStringName ContextA或者 -
Update-Database -ConfigurationTypeName ConfigurationB -ProjectName ProjectContextIsInIfNotMainOne -StartupProjectName NameOfMainProject -ConnectionStringName ContextB
回答by bart s
I just bumped into the same problem and I used the following solution (all from Package Manager Console)
我刚刚遇到了同样的问题,我使用了以下解决方案(全部来自包管理器控制台)
PM> Enable-Migrations -MigrationsDirectory "Migrations\ContextA" -ContextTypeName MyProject.Models.ContextA
PM> Enable-Migrations -MigrationsDirectory "Migrations\ContextB" -ContextTypeName MyProject.Models.ContextB
This will create 2 separate folders in the Migrations folder. Each will contain the generated Configuration.csfile. Unfortunately you still have to rename those Configuration.csfiles otherwise there will be complaints about having two of them. I renamed my files to ConfigA.csand ConfigB.cs
这将在 Migrations 文件夹中创建 2 个单独的文件夹。每个都将包含生成的Configuration.cs文件。不幸的是,您仍然必须重命名这些Configuration.cs文件,否则会有关于其中两个文件的投诉。我将我的文件重命名为ConfigA.cs和ConfigB.cs
EDIT: (courtesy Kevin McPheat) Remember when renaming the Configuration.cs files, also rename the class names and constructors /EDIT
编辑:(由 Kevin McPheat 提供)记住重命名 Configuration.cs 文件时,还要重命名类名和构造函数/EDIT
With this structure you can simply do
有了这个结构,你可以简单地做
PM> Add-Migration -ConfigurationTypeName ConfigA
PM> Add-Migration -ConfigurationTypeName ConfigB
Which will create the code files for the migration inside the folder next to the config files (this is nice to keep those files together)
这将在配置文件旁边的文件夹中创建用于迁移的代码文件(将这些文件保存在一起很好)
PM> Update-Database -ConfigurationTypeName ConfigA
PM> Update-Database -ConfigurationTypeName ConfigB
And last but not least those two commands will apply the correct migrations to their corrseponding databases.
最后但并非最不重要的是,这两个命令会将正确的迁移应用于其相应的数据库。
EDIT 08 Feb, 2016:I have done a little testing with EF7 version 7.0.0-rc1-16348
编辑 2016 年 2 月 8 日:我对 EF7 版本 7.0.0-rc1-16348 进行了一些测试
I could not get the -o|--outputDir option to work. It kept on giving Microsoft.Dnx.Runtime.Common.Commandline.CommandParsingException: Unrecognized command or argument
我无法使用 -o|--outputDir 选项。它继续给予Microsoft.Dnx.Runtime.Common.Commandline.CommandParsingException: Unrecognized command or argument
However it looks like the first time an migration is added it is added into the Migrations folder, and a subsequent migration for another context is automatically put into a subdolder of migrations.
然而,它看起来像是第一次添加迁移时将其添加到 Migrations 文件夹中,并且随后针对另一个上下文的迁移会自动放入迁移的子目录中。
The original names ContextAseems to violate some naming conventions so I now use ContextAContextand ContextBContext. Using these names you could use the following commands:
(note that my dnx still works from the package manager console and I do not like to open a separate CMD window to do migrations)
原始名称ContextA似乎违反了一些命名约定,因此我现在使用ContextAContext和ContextBContext。使用这些名称,您可以使用以下命令:(请注意,我的 dnx 仍然可以从包管理器控制台运行,而且我不喜欢打开单独的 CMD 窗口来进行迁移)
PM> dnx ef migrations add Initial -c "ContextAContext"
PM> dnx ef migrations add Initial -c "ContextBContext"
This will create a model snapshot and a initial migration in the Migrationsfolder for ContextAContext. It will create a folder named ContextBcontaining these files for ContextBContext
这将在Migrations文件夹中创建模型快照和初始迁移ContextAContext。它将创建一个名为ContextB包含这些文件的文件夹ContextBContext
I manually added a ContextAfolder and moved the migration files from ContextAContextinto that folder. Then I renamed the namespace inside those files (snapshot file, initial migration and note that there is a third file under the initial migration file ... designer.cs). I had to add .ContextAto the namespace, and from there the framework handles it automatically again.
我手动添加了一个ContextA文件夹并将迁移文件从ContextAContext该文件夹中移入。然后我重命名了这些文件中的命名空间(快照文件、初始迁移并注意初始迁移文件下还有第三个文件...designer.cs)。我不得不添加.ContextA到命名空间,然后框架再次自动处理它。
Using the following commands would create a new migration for each context
使用以下命令将为每个上下文创建一个新的迁移
PM> dnx ef migrations add Update1 -c "ContextAContext"
PM> dnx ef migrations add Update1 -c "ContextBContext"
and the generated files are put in the correct folders.
并将生成的文件放在正确的文件夹中。
回答by Guillermo Ruffino
In case you already have a "Configuration" with many migrations and want to keep this as is, you can always create a new "Configuration" class, give it another name, like
如果您已经有一个包含许多迁移的“配置”并希望保持原样,您可以随时创建一个新的“配置”类,给它另一个名称,例如
class MyNewContextConfiguration : DbMigrationsConfiguration<MyNewDbContext>
{
...
}
then just issue the command
然后只需发出命令
Add-Migration -ConfigurationTypeName MyNewContextConfiguration InitialMigrationName
and EF will scaffold the migration without problems. Finally update your database, from now on, EF will complain if you don't tell him which configuration you want to update:
EF 将毫无问题地支持迁移。最后更新你的数据库,从现在开始,如果你不告诉他你要更新哪个配置,EF会抱怨:
Update-Database -ConfigurationTypeName MyNewContextConfiguration
Done.
完毕。
You don't need to deal with Enable-Migrations as it will complain "Configuration" already exists, and renaming your existing Configuration class will bring issues to the migration history.
您不需要处理 Enable-Migrations,因为它会抱怨“Configuration”已经存在,并且重命名现有的 Configuration 类会给迁移历史带来问题。
You can target different databases, or the same one, all configurations will share the __MigrationHistory table nicely.
您可以针对不同的数据库,也可以针对相同的数据库,所有配置将很好地共享 __MigrationHistory 表。
回答by AHAMED AAQIB
If more databases exist use following codes in PowerShell
如果存在更多数据库,请在 PowerShell 中使用以下代码
Add-Migration Starter -context EnrollmentAppContext
'Starter' is Migration Name
'EnrollmentAppContext' is name of my app Context
'Starter' 是迁移名称
'EnrollmentAppContext' 是我的应用程序上下文的名称
You can open PowerShell in VS by doing:
Tools->NuGet Package Manager->Package Manager Console
您可以通过执行以下操作在 VS 中打开 PowerShell:
Tools->NuGet Package Manager->Package Manager Console
回答by AHAMED AAQIB
To update database type following codes in PowerShell...
要在 PowerShell 中更新数据库类型以下代码...
Update-Database -context EnrollmentAppContext
*if more than one databases exist only use this codes,otherwise not necessary..
*如果存在多个数据库,则仅使用此代码,否则不需要..
回答by Davit Mikuchadze
EF 4.7 actually gives a hint when you run Enable-migrations at multiple context.
当您在多个上下文中运行 Enable-migrations 时,EF 4.7 实际上会给出提示。
More than one context type was found in the assembly 'Service.Domain'.
在程序集“Service.Domain”中发现了不止一种上下文类型。
To enable migrations for 'Service.Domain.DatabaseContext.Context1',
use Enable-Migrations -ContextTypeName Service.Domain.DatabaseContext.Context1.
To enable migrations for 'Service.Domain.DatabaseContext.Context2',
use Enable-Migrations -ContextTypeName Service.Domain.DatabaseContext.Context2.

