I\'ve recently started using Entity Framework migrations and noticed that the database name is not pulling through for me when I run the Update-Database
command
When doing update-database
you should specify the project that contains the migrations. Make sure that you have an app.config
file in that project that contains the correct connection string.
When splitting up an application over several projects, the connection string used when running the app is the one of the project started. When migrating, the connection string used is the one of the project containing the migrations.
When I did a similar setup I had to add the connection string in two places. A bit awkward, but it works.
However Update-Database
does not read the App.config
from the project that contain the migrations (just like the answer 1 year ago) but it will only read *.config
from start up project. It is great but I discover how Add-Migration
and Update-Database
find a suitable connection string here:
MyContext
class derived from DbContext
so I can use the "MyContext" connection string name. Useful when I have multiple db connections.-ConnectionStringName
parameter. See get-help Update-Database
to view the help page in the Package Manager Console.There is no retry or fallback attempt, so if the "DefaultConnection" contains a wrong connection string, it will simply show an error.
If both DefaultConnection and context name exist in the connection strings, DefaultConnection will take precedence.
I would prefer #2 become the first try because the name is more specific but the above steps is what EF5 Migrations do when trying to connect to the db.
You can have your connection string stored in the web.config in your website project and the DBContext and migration files in another project and still share the same connection string. However you need to make sure that as well as setting the Data project (or whatever project has the DBContext etc. in it) as the default project for the Package Manager Console, you ALSO need to make sure that your website is set to the Default StartUp Project!!!
I cannot see this documented anywhere, but a frantic 24 hours of not being able to figure out why my migrations where suddenly being applied to a SQLExpress db, led me to this conclusion.
You can avoid managing it in app.config by offering it as a parameter:
Update-Database -Verbose
-ConnectionString "CONNECTIONSTRING"
-ConnectionProviderName "System.Data.SqlClient"
-StartupProjectName WEBSITE_PROJECT -ProjectName MIGRATION_PROJECT
Easy-piezy, if you love to type endlessly.