Entity Framework 6 (EF6) code first migrations with models in separate project

假如想象 提交于 2019-12-12 02:06:05

问题


Using EF6 code-first migrations, I am able to successfully save models and create new migrations for them. However, my DbContext class is in a Sharp.Data project, the actual (Sql CE) database lives under the Sharp.Server project bin folder, and my models live in a Sharp.Common project.

When I run add-migration -ProjectName Sharp.Data Migration3 (pointing to Sharp.Data as that is where the DbContext is), it successfully runs and identifies changes made to the models in the Sharp.Common project. However, when I run update-database -ProjectName Sharp.Data, it updates/creates/migrates/seeds a new database located under the bin folder of my Sharp.Data project, instead of Sharp.Server, where ultimately the application reads the data from.

Is there a way to do this? To have migrations generate/update a database that exists somewhere else besides its own project file? This may be a relic of using SQL CE, but it's my database of choice for various reasons.


回答1:


You can pass extra parameters to update-database that allow to:

  • Specify a different connection string
  • Generate a SQL script that you can apply yourself to the target DB

Full syntax of Update-Database:

Update-Database [-SourceMigration <String>] [-TargetMigration <String>]
[-Script] [-Force] [-ProjectName <String>] [-StartUpProjectName <String>] 
[-ConfigurationTypeName <String>] [-ConnectionStringName <String>] 
[<CommonParameters>]

Update-Database [-SourceMigration <String>] [-TargetMigration <String>] 
[-Script] [-Force] [-ProjectName <String>] [-StartUpProjectName <String>] 
[-ConfigurationTypeName <String>] -ConnectionString <String> 
-ConnectionProviderName <String> [<CommonParameters>]

To specify a connection string (which points to the correct folder in your project):

  • -StartUpProjectName and -ConnectionStringName, to specify a project that contains a .config file with a connection string with the provided name (1st syntax)
  • -ConnectionString, to specify directly the connection string (2nd syntax)

To create a SQL script that you can apply directly to the DB using other tool:

  • -SourceMigration: current migration in the destination DB -TargetMigration: migration to update to, and -Script: to generate a script taht you can apply by hand



回答2:


@JotaBe's answer is correct. But to summise, you need to do the following:

add-migration "MigrationName" -ProjectName Sharp.Data -ConnectionString "ConnectionStringToYourTargetDatabaseHere"


来源:https://stackoverflow.com/questions/23621912/entity-framework-6-ef6-code-first-migrations-with-models-in-separate-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!