I have an application using Entity Framework Core to create an SQL Server database and its tables by applying migrations. I need to be able to specify the directory location where the database files will be created.
What I want to be able to do is either:
Have my application create the database with its files in the specified location before applying migrations
Have my application tell SQL Server where to create the database files, before applying migrations
I'm creating my DbContext
using the connection string:
Data Source=ServerName;AttachDbFilename=specifiedPath\databasename.mdf;Initial Catalog=databasename;Integrated Security=True
I've tried having the application create the database using a standard SQL Create query before applying migrations. This causes the migrations to fail with the following exception:
Microsoft.Data.SqlClient.SqlException (0x80131904): Database 'databasename' already exists. Choose a different database name.
I assume this is because the DbContext
or migrations are trying to create the database specified in the connection string.
Could I somehow edit the migration to remove the step where it creates the database? Or the DbContext
?
Just in case anybody is looking to solve a similar problem:
I solved this by simply removing my code that checked if the database already existed. There's actually no need to manually create the file at all.
By specifying the file name in the connection string, using the
AttachDbFilename=specifiedPath\databasename.mdf
parameter, SQL server just created the file in that location.
User contributions licensed under CC BY-SA 3.0