EF Migrations series
- Using Entity Framework to Create a Database
- Adding Indexes with EF Migrations
- Updating a Table with EF Migrations
- Indexes in Code-Based EF Migrations
- EF Migrations and a Merge Conflict
- Prevent EF Migrations from Creating or Changing the Database
- EF Code First Change Tracking
- EF Migrations Command Reference
- EF Code First Navigation Properties and Foreign Keys
- Update-Database MSI Custom Action
Entity Framework Migrations are handled from the package manager console in Visual Studio. The usage is shown in various tutorials, but I haven’t found a complete list of the commands available and their usage, so I created my own. There are four available main commands.
- Enable-Migrations: Enables Code First Migrations in a project.
- Add-Migration: Scaffolds a migration script for any pending model changes.
- Update-Database: Applies any pending migrations to the database.
- Get-Migrations: Displays the migrations that have been applied to the target database.
This post was updated 2014-07-02 with Entity Framework 6.1.1
There are also three extra commands that are used by NuGet packages that install Entity Framework providers. These commands are not usually used as part of normal application development.
There are also three extra commands that are used by NuGet packages that install Entity Framework providers. These commands are not usually used as part of normal application development.
- Add-EFProvider: Adds or updates an Entity Framework provider entry in the project config file.
- Add-EFDefaultConnectionFactory: Adds or updates an Entity Framework default connection factory in the project config file.
- Initialize-EFConfiguration: Initializes the Entity Framework section in the project config file and sets defaults.
The information here is the output of running 4.3.1 6.1.1). I’ve also added some own comments where I think some information is missing. My own comments are placed under the Additional Information heading.
get-help command-name -detailed
for each of the commands in the package manager console (running EF
Please note that all commands should be entered on the same line. I’ve added line breaks to avoid horizontal scrollbars.
Enable-Migrations
Enables Code First Migrations in a project.
Syntax
Description
Enables Migrations by scaffolding a migrations configuration class in the project. If the target database was created by an initializer, an initial migration will be created (unless automatic migrations are enabled via the EnableAutomaticMigrations parameter).
Parameters
-ContextTypeName <String>
Specifies the context to use. If omitted, migrations will attempt to locate a single context type in the target project.
-EnableAutomaticMigrations [<SwitchParameter>]
Specifies whether automatic migrations will be enabled in the scaffolded migrations configuration. If ommitted, automatic migrations will be disabled.
-MigrationsDirectory <String>
Specifies the name of the directory that will contain migrations code files. If omitted, the directory will be named “Migrations”.
-ProjectName <String>
Specifies the project that the scaffolded migrations configuration class will be added to. If omitted, the default project selected in package manager console is used.
-StartUpProjectName <String>
Specifies the configuration file to use for named connection strings. If omitted, the specified project’s configuration file is used.
-ContextProjectName <String>
Specifies the project which contains the DbContext class to use. If omitted, the context is assumed to be in the same project used for migrations.
-ConnectionStringName <String>
Specifies the name of a connection string to use from the application’s configuration file.
-ConnectionString <String>
Specifies the the connection string to use. If omitted, the context’s default connection will be used.
-ConnectionProviderName <String>
Specifies the provider invariant name of the connection string.
-Force [<SwitchParameter>]
Specifies that the migrations configuration be overwritten when running more than once for given project.
-ContextAssemblyName <String>
Specifies the name of the assembly which contains the DbContext class to use. Use this parameter instead of ContextProjectName when the context is contained in a referenced assembly rather than in a project of the solution.
-AppDomainBaseDirectory <String>
Specifies the directory to use for the app-domain that is used for running Migrations code such that the app-domain is able to find all required assemblies. This is an advanced option that should only be needed if the solution contains several projects such that the assemblies needed for the context and configuration are not all referenced from either the project containing the context or the project containing the migrations.
<CommonParameters>
This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer, PipelineVariable, and OutVariable. For more information, seeabout_CommonParameters.
Examples
Remarks
To see the examples, type:
For more information, type:
For technical information, type:
get-help Enable-Migrations -examples
.For more information, type:
get-help Enable-Migrations -detailed
.For technical information, type:
get-help Enable-Migrations -full
.Additional Information
The flag for enabling automatic migrations is saved in the
Migrations\Configuration.cs
file, in the constructor. To later change the option, just change the assignment in the file.Add-Migration
Scaffolds a migration script for any pending model changes.
Syntax
Description
Scaffolds a new migration script and adds it to the project.
Parameters
-Name <String>
Specifies the name of the custom script.
-Force [<SwitchParameter>]
Specifies that the migration user code be overwritten when re-scaffolding an existing migration.
-ProjectName <String>
Specifies the project that contains the migration configuration type to be used. If ommitted, the default project selected in package manager console is used.
-StartUpProjectName <String>
Specifies the configuration file to use for named connection strings. If omitted, the specified project’s configuration file is used.
-ConfigurationTypeName <String>
Specifies the migrations configuration to use. If omitted, migrations will attempt to locate a single migrations configuration type in the target project.
-ConnectionStringName <String>
Specifies the name of a connection string to use from the application’s configuration file.
-ConnectionString <String>
Specifies the the connection string to use. If omitted, the context’s default connection will be used.
-ConnectionProviderName <String>
Specifies the provider invariant name of the connection string.
-IgnoreChanges
Scaffolds an empty migration ignoring any pending changes detected in the current model. This can be used to create an initial, empty migration to enable Migrations for an existing database. N.B. Doing this assumes that the target database schema is compatible with the current model.
-AppDomainBaseDirectory <String>
Specifies the directory to use for the app-domain that is used for running Migrations code such that the app-domain is able to find all required assemblies. This is an advanced option that should only be needed if the solution contains several projects such that the assemblies needed for the context and configuration are not all referenced from either the project containing the context or the project containing the migrations.
<CommonParameters>
This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer, PipelineVariable, and OutVariable. For more information, seeabout_CommonParameters.
<CommonParameters>
Remarks
To see the examples, type:
For more information, type:
For technical information, type:
get-help Add-Migration -examples
.For more information, type:
get-help Add-Migration -detailed
.For technical information, type:
get-help Add-Migration -full
.Update-Database
Applies any pending migrations to the database.
Syntax
Description
Updates the database to the current model by applying pending migrations.
Parameters
-SourceMigration <String>
Only valid with -Script. Specifies the name of a particular migration to use as the update’s starting point. If ommitted, the last applied migration in the database will be used.
-TargetMigration <String>
Specifies the name of a particular migration to update the database to. If ommitted, the current model will be used.
-Script
Generate a SQL script rather than executing the pending changes directly.
-Force
Specifies that data loss is acceptable during automatic migration of the database.
-ProjectName <String>
Specifies the project that contains the migration configuration type to be used. If ommitted, the default project selected in package manager console is used.
-StartUpProjectName <String>
Specifies the configuration file to use for named connection strings. If omitted, the specified project’s configuration file is used.
-ConfigurationTypeName <String>
Specifies the migrations configuration to use. If omitted, migrations will attempt to locate a single migrations configuration type in the target project.
-ConnectionStringName <String>
Specifies the name of a connection string to use from the application’s configuration file.
-ConnectionString <String>
Specifies the the connection string to use. If omitted, the context’s default connection will be used.
-ConnectionProviderName <String>
Specifies the provider invariant name of the connection string.
-AppDomainBaseDirectory <String>
Specifies the directory to use for the app-domain that is used for running Migrations code such that the app-domain is able to find all required assemblies. This is an advanced option that should only be needed if the solution contains several projects such that the assemblies needed for the context and configuration are not all referenced from either the project containing the context or the project containing the migrations.
<CommonParameters>
This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer, PipelineVariable, and OutVariable. For more information, seeabout_CommonParameters.
Examples
Remarks
To see the examples, type:
For more information, type:
For technical information, type:
get-help Update-Database -examples
.For more information, type:
get-help Update-Database -detailed
.For technical information, type:
get-help Update-Database -full
.Additional Information
The command always runs any pending code-based migrations first. If the database is still incompatible with the model the additional changes required are applied as an separate automatic migration step if automatic migrations are enabled. If automatic migrations are disabled an error message is shown.
Get-Migrations
Displays the migrations that have been applied to the target database.
Syntax
Description
Displays the migrations that have been applied to the target database.
Parameters
-ProjectName <String>
Specifies the project that contains the migration configuration type to be used. If ommitted, the default project selected in package manager console is used.
-StartUpProjectName <String>
Specifies the configuration file to use for named connection strings. If omitted, the specified project’s configuration file is used.
-ConfigurationTypeName <String>
Specifies the migrations configuration to use. If omitted, migrations will attempt to locate a single migrations configuration type in the target project.
-ConnectionStringName <String>
Specifies the name of a connection string to use from the application’s configuration file.
-ConnectionString <String>
Specifies the the connection string to use. If omitted, the context’s default connection will be used.
-ConnectionProviderName <String>
Specifies the provider invariant name of the connection string.
-AppDomainBaseDirectory <String>
Specifies the directory to use for the app-domain that is used for running Migrations code such that the app-domain is able to find all required assemblies. This is an advanced option that should only be needed if the solution contains several projects such that the assemblies needed for the context and configuration are not all referenced from either the project containing the context or the project containing the migrations.
<CommonParameters>
This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer, PipelineVariable, and OutVariable. For more information, seeabout_CommonParameters.
Remarks
To see the examples, type:
For more information, type:
For technical information, type:
get-help Get-Migrations -examples
.For more information, type:
get-help Get-Migrations -detailed
.For technical information, type:
get-help Get-Migrations -full
.Add-EFProvider
Adds or updates an Entity Framework provider entry in the project config file.
Syntax
Add-EFProvider [-Project] <Object> [-InvariantName] <String> [-TypeName] <String> [<CommonParameters>]
Description
Adds an entry into the ‘entityFramework’ section of the project config file for the specified provider invariant name and provider type. If an entry for the given invariant name already exists, then that entry is updated with the given type name, unless the given type name already matches, in which case no action is taken. The ‘entityFramework’ section is added if it does not exist. The config file is automatically saved if and only if a change was made.
This command is typically used only by Entity Framework provider NuGet packages and is run from the ‘install.ps1′ script.
Parameters
-Project <Object>
The Visual Studio project to update. When running in the NuGet install.ps1 script the ‘$project’ variable provided as part of that script should be used.
-InvariantName <String>
The provider invariant name that uniquely identifies this provider. For example, the Microsoft SQL Server provider is registered with the invariant name ‘System.Data.SqlClient’.
-TypeName <String>
The assembly-qualified type name of the provider-specific type that inherits from ‘System.Data.Entity.Core.Common.DbProviderServices’. For example, for the Microsoft SQL Server provider, this type is ‘System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer’.
<CommonParameters>
This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer, PipelineVariable, and OutVariable. For more information, seeabout_CommonParameters.
Remarks
To see the examples, type:
For more information, type:
For technical information, type:
get-help Add-EFProvider -examples
.For more information, type:
get-help Add-EFProvider -detailed
.For technical information, type:
get-help Add-EFProvider -full
.Add-EFDefaultConnectionFactory
Adds or updates an Entity Framework default connection factory in the project config file.
Syntax
Description
Adds an entry into the ‘entityFramework’ section of the project config file for the connection factory that Entity Framework will use by default when creating new connections by convention. Any existing entry will be overridden if it does not match. The ‘entityFramework’ section is added if it does not exist. The config file is automatically saved if and only if a change was made.
This command is typically used only by Entity Framework provider NuGet packages and is run from the ‘install.ps1′ script.
Parameters
-Project <Object>
The Visual Studio project to update. When running in the NuGet install.ps1 script the ‘$project’ variable provided as part of that script should be used.
-TypeName <String>
The assembly-qualified type name of the connection factory type that implements the ‘System.Data.Entity.Infrastructure.IDbConnectionFactory’ interface. For example, for the Microsoft SQL Server Express provider
connection factory, this type is ‘System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework’.
connection factory, this type is ‘System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework’.
-ConstructorArguments <String[]>
An optional array of strings that will be passed as arguments to the connection factory type constructor.
<CommonParameters>
This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer, PipelineVariable, and OutVariable. For more information, seeabout_CommonParameters.
Remarks
To see the examples, type:
For more information, type:
For technical information, type:
get-help Add-EFDefaultConnectionFactory -examples
.For more information, type:
get-help Add-EFDefaultConnectionFactory -detailed
.For technical information, type:
get-help Add-EFDefaultConnectionFactory -full
.Initialize-EFConfiguration
Initializes the Entity Framework section in the project config file and sets defaults.
Syntax
Description
Creates the ‘entityFramework’ section of the project config file and sets the default connection factory to use SQL Express if it is running on the machine, or LocalDb otherwise. Note that installing a different provider may change the default connection factory. The config file is automatically saved if and only if a change was made.
In addition, any reference to ‘System.Data.Entity.dll’ in the project is removed.
This command is typically used only by Entity Framework provider NuGet packages and is run from the ‘install.ps1′ script.
Parameters
-Project <Object>
The Visual Studio project to update. When running in the NuGet install.ps1 script the ‘$project’ variable provided as part of that script should be used.
<CommonParameters>
This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer, PipelineVariable, and OutVariable. For more information, seeabout_CommonParameters.
Remarks
To see the examples, type:
For more information, type:
For technical information, type:
get-help Initialize-EFConfiguration -examples
.For more information, type:
get-help Initialize-EFConfiguration -detailed
.For technical information, type:
get-help Initialize-EFConfiguration -full
.Additional Information
The powershell commands are complex powershell functions, located in the
YJY5P7USBQXS
tools\EntityFramework.psm1
file of the Entity Framework installation. The powershell code is mostly a wrapper around theSystem.Data.Entity.Migrations.MigrationsCommands
found in thetools\EntityFramework\EntityFramework.PowerShell.dll
file. First a MigrationsCommands
object is instantiated with all configuration parameters. Then there is a public method on the MigrationsCommands
object for each of the available commands.YJY5P7USBQXS
- Pingback: TicketDesk 3 Dev Diary – EF Migrations & TD2 Upgrades – Part 2 | The Scribbler on 2013-01-27
- Pingback: Commands with Entity Framework’s migration | Nguyen Quy Hy's Blog on 2013-09-11
- Pingback: Integration Testing Entity Framework with Migrations on 2014-07-31
Albin Sunnanbo on 2012-03-19
Note that there is a special migration-step,$InitialDatabase
, available that denotes an empty database. Usage:Instead of$InitialDatabase
you can also use the name0
.MadDog on 2012-04-19
Is there a way to specify schema when creating a table usingUpdate-Database
?(in SQLServer2008)
When I run on local SQLExpress it all looks fine, but when I connect to the SQLServer 2008 DEV server all the tables get created with"my schema"
– however I want to have
.MyTableNamedbo.MyTableName
as the name of the table.Any ideas?Cheers,
LAnders Abel on 2012-05-01
I’ve played around a bit with schemas and haven’t got it to work from EF Code First. I got as far as having the tables created in different schemas, but then the queries failed. The only option I can think of is to set the default schema for the user that connects to the database. You could try asking a question on Stack Overflow and tag it withef-migrations
. There are some people active there that knows EF migrations really well.Gilles Leblanc on 2013-04-11
Thank you! This documentation was very useful. I tried finding info on MSDN but wasn’t coming up with what I needed.If you had a “Like” button or similar I would have clicked!Continue your great work and thanks again.Jesper Lund Stocholm on 2014-02-18
Hi Anders,Great article!I am trying to figure out how to do migrations (update-database) via powershell script directly. When looking at the help for the script, the arguments are more or less the same as when using it thru Package Manager Console. However, I cannot see a way to point the PS script to the DLL containing the migration code.I want to use it to do migrations when building on TFS and at that point I am no longer “in Visual Studio” and cannot point to neither a “Default project” og anything similar.Do you know of a way to specify to the PS script that it should execute the code in “the assembly located at …”?Thanks,:-)/Jesper
CopenhagenAnders Abel on 2014-02-18
The cmd-lets used within Visual Studio are very tightly coupled to the VS environment (see http://stackoverflow.com/questions/17093288/scripting-ef-add-migration-into-an-automated-build-task/17105602#17105602).There is however a separate tool migrate.exe that is included in the nuget package for EF. It can be used to run migrations from the command line and should work with powershell.Roman on 2014-06-10
Sometimes I need more information about what ef do and the “–Verbose” flag is very usefull for that)Ryan Liu on 2014-06-10
Good stuff, Anders. Thanks a lot. It saved my time. It’s disappointing that Microsoft does not come out such reference but just some basic tutorials.
hi
ReplyDeletethanks, that was very useful ....