I am using Entity-Framework in a Winforms application. The application connects to MSSQLServer and everything works fine. Then I detach the database and copy the .mdf
file to the app folder and change the connection string to use the local .mdf
file, still everything works fine.
The problem is that when I copy my application together with the database to another PC suddenly EF tries to recreate the database and throws this error:
Cannot create file 'Path\MyDatabaseName.mdf' because it already exists. Change the file path or the file name, and retry the operation. CREATE DATABASE failed. Some file names listed could not be created. Check related errors.
Context Initializer is set to MigrateDatabaseToLatestVersion
:
Database.SetInitializer<MyContext>(new MigrateDatabaseToLatestVersion<MyContext, DAL.Migrations.Configuration>("MyConnectionString"));
Also, automatic migration is off and database is created by EF Code-First on Sql-server and is already updated to the latest migration so no migration is needed.
Connection string for the first scenario is:
<add name="MyConnectionString" connectionString="Server=DESKTOP-XXXXXXX; Database=MyDatabase; Integrated Security=True; Connect Timeout=30;" providerName="System.Data.SqlClient">
and for local .mdf
file is:
<add name="MyConnectionString" connectionString="Data Source=(LocalDB)\MSSQLLocalDB; AttachDbFilename=|DataDirectory|\MyDatabase.mdf; Integrated Security=True;Connect Timeout=30" providerName="System.Data.SqlClient" />
So, What is going on here??
|DataDirectory|
. – Downright|DataDirectory|
folder. So we can be sure that the path is correct. Basically this is the confusing part: EF ignores the existence of the database file and tries to overwrite it with a new file. – Nagey