Cannot create file '*.mdf' because it already exists - c#

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??

In my case, go to C:\Program Files\Microsoft SQL Server\SQLSERVER\MSSQL\DATA folder and delete the same database name '*.mdf' file if exist. After deleting it and recreate the database, the problem is resolved.

Related

Switch from LocalDB to SQL Server DB MVC5

I have a MVC5 project with individual authentication.
Now I want to move from (localdb)\MSSQLLocalDB to another SQL Server database.
I've tried to change connection string from this :
Data Source=(localdb)\MSSQLLocalDB;Integrated Security=True;Connect
Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False
to this:
Data Source=PC-GABRI;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False
And the application is still using localDB instead of my new SQL Server DB.
I have already migrated the database and roles.
I have also tried to comment all of my connection string form Web.Config but my application is still working and I can login with my "test" user.
I can't find anything on the web about this!
PS.
Related Questions: Switch LocalDB to SQL server db with MVC5
We have the same problem!
UPDATE 1
DB Instance:
Connection String:
The instances are running correctly.
Tell me if you need more info.
UPDATE
This Guide was very useful for me :
https://danieleagle.com/2014/05/setting-up-asp-net-identity-framework-2-0-with-database-first-vs2013-update-2-spa-template/
Follow all the easy steps for move your LocalDB table to SQL server db Table.
1. Inspect the Web.config File Connection String and Connect to Local Database
Change the defaut connection string:
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-WebApp-20190226025646.mdf;Initial Catalog=aspnet-WebApp-20190226025646;Integrated Security=True" providerName="System.Data.SqlClient" />
To your connection string:
<add name="DefaultConnection" connectionString="Data Source=PC-YWGSB;Initial Catalog=WebApp;user id=admin;password=admin" providerName="System.Data.SqlClient" />
2. Then use the commands for DB Migration "Codefirst"
This is the official guide:
https://learn.microsoft.com/it-it/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/migrations-and-deployment-with-the-entity-framework-in-an-asp-net-mvc-application
From the Tools menu, select NuGet Package Manager > Package Manager Console.
At the PM> prompt enter the following commands:
enable-migrations
add-migration InitialCreate
update-database
The database will be created automatically during migration.
If you already have one make sure to backup all tables.

LocalDB not found when deploying to a different machine

I'm having a problem switching a project I am working on over to another system. It's an ASP.Net web application and web form wrapped in a single solution, with a SQL .mdf DB file in the project as well. I'd like to be able to zip up the whole thing and move it around, but when trying to debug the solution on the other machine I get an error about the local DB not existing. My connection string in the Web.Config file looks like this:
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-name-of-database.mdf;Initial Catalog=aspnet-name-of-database;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
I know I must be making an obvious mistake, but I can't figure out what it is. Any advice, please? Thanks.
Edit: The specific error is:
"The specified LocalDB instance does not exist."
Run the following from your package manager console:
SqlLocalDb info
If the executable isn’t found, chances are you do not have LocalDb installed in your new machine. You can use the steps mentioned in the below link to debug as to why the connection is not successful to your localDB:
http://odetocode.com/blogs/scott/archive/2012/08/15/a-troubleshooting-guide-for-entity-framework-connections-amp-migrations.aspx
Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True
Try setting the Datasource as below.
Data Source=.\;
If you are able to connect to your database, then the set the ServerName as DataSource in your connection string.
Make sure you have SSMS installed in your new system.
Download SQL Server Express 2014

mdf database dosen't update data from bin\Debug folder into main folder

This is my connection string:
<add name ="myConfig"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Platform.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
and the class that uses that connection string:
internal static SqlConnection Connection
{
get
{
AppDomain.CurrentDomain.SetData("DataDirectory",#"C:\Users\Marius\Documents\Visual Studio 2012\Projects\BidingPlatform2014\BidingPlatform2014\Platform.mdf");
return new SqlConnection(myString);
}
}
I am using Visual Studio 2012 and SQL Sever 2012.
But after my application closes data isn't saved into my primary database (database that I see under Server Explorer > Data Connection).
I think that data is stored during the execution into a copy of database located under bin\Debug folder.
How I update data into my original database.
Sincerely,
First, just do the call to AppDomain.CurrentDomain.SetData just one time when your app starts and before any activity on the database. There is no need to repeat it (and has no effect once the first call to the database is made) every time you ask for the connection.
Second, |DataDirectory| should be a folder, not the full path to the MDF file
AppDomain.CurrentDomain.SetData("DataDirectory",
#"C:\Users\Marius\Documents\Visual Studio 2012\Projects\BidingPlatform2014\BidingPlatform2014");

Switch DB From local SQL to AZURE DB with MVC5 App

I've Create MVC5 APP with Local DB like the following link(step 1 to 5)
http://www.asp.net/mvc/tutorials/mvc-5/database-first-development/creating-the-web-application
And the application is running as expected and now I need to change the DB from the
sql Lite to azure DB ,I have created the same DB in azure (same data structure)and now what I want that the application use this DB ,There is simple way to do that ?
Im using VS2013 for web.
Just change the "source" and "initial catalog" parameters of the connection string in the web.config file.
Also, SQL Azure doesn't work with integrated security so you need to remove the "integrated security" parameter from the connection string and add the parameters "User ID" and "Password" with the credential of a user that you created in SQL Azure.
Open Visual Studio In Solution Explorer
find the file web.config
Look for the section connectionStrings
You should find something similar to:
<add name="testEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\test.mdf;integrated security=True;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
You need to:
Replace (LocalDB)\v11.0 with the name of your server
Remove "attachdbfilename=|DataDirectory|\test.mdf;integrated security=True;"
Add "Initial catalog=[name of your database in SQL Azure];user id=[name of your user id on SQL Azure];password=[your password]

Migrating the database file of ASP.NET MVC3

I just started using C# and MVC3, and I've been following the MVCMusicStore tutorial at ASP.NET website.. In the tutorial it used
<add name="MusicStoreEntities"
connectionString="Data Source=|DataDirectory|MvcMusicStore.sdf"
providerName="System.Data.SqlServerCe.4.0"/>
as the connection string... In my application I changed it to
<add name="FashionStyle.StoreEntities"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|FashionStyle.StoreEntities.mdf;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient"/>
But I found out the actual database file is in
C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA
My question is how do I move it from there to the App_Data folder in the project and make it so that Visual Studio 2010 will know where to look for the database file? This is because the application is a group work and I want to share it with my team members.
actually what they have used is .sdf file ie., Sql Server Compact Database file and what you are using is .mdf file which is a Sql Server Database file.
now if you have created that database either through VS Server Explorer or Sql Server Management Studio then I think you dont have to worry, just use
<add name="FashionStyle.StoreEntities"
connectionString="Data Source=.\SQLEXPRESS;
Initial Catalog=yourDatabase;
Integrated Security=True;
User Instance=True";
providerName="System.Data.SqlClient"/>
Visual Studio will only know where to find it if you tell it where to find it. Simply backup the database using standard SQL Server procedures and restore it where is most appropriate then update your appconfig/webconfig + Server Explorer to point to it.

Categories

Resources