Cannot create file because it already exists. Change the file path or the file name, and retry the operation - sql

I created an asp.net mvc website with a code first database. I enabled database migration through the PM Console. I uploaded the website and database on to a server for online testing. I now want to do additional testing on my desktop so I downloaded the existing databases and placed them in the App_Data file.
Using the PM Console, I run the Update-Database command and the response is as follows:
PM> Update-Database
Specify the '-Verbose' flag to view the SQL
statements being applied to the target database. No pending explicit
migrations. Running Seed method.
I suspect that the database's schema is recognized as unchanged.
However, when I go to debug the website using localhost, after entering in username and password, I get the following error:
Cannot create file 'C:\Users\XXXX\OneDrive\Visual Studio
2017\Projects\Testing\XXXXXX\Version
2.4\XXXXXX\App_Data\DB_9AEA79_data.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.
I can't figure out why VS wants to re-create a database I've placed in the App_Data folder.
Any help would be greatly appreciated.

That’s because localDb uses an SqlServerExpress-Instance to use the database.
You can attach the file to the instance, but if you only copy the file it fails.
I didn’t check it and it’s old, but maybe the Docs can help you.

I am a newbie and this is my first post on this site, but I hope my post will help someone. I have the same message and for a long time I could not understand what is going on.
Cannot create file '' 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.
I created an asp.net mvc project with an ms sql database and Entity Framework (code first). After creating the database, I immediately opened MS SQL Server Management Studio and added the database. After closing and reopening Visual Studio I always saw the same error (if I don't close VS everything works correctly).
It turned out to be caused by connection to MS SQL Server Management Studio. It's not enough to close the program, or to disable the connection.
Here's what needs to be done.
MS SQL SMS
I hope this helps someone.

Related

EntityFramework 7 database already exists error on migrations

ASP.NET 5 project, Entity Framework 7. Using all the default stuff that comes with the ASP.NET 5 web template for creating the Identity Context. When I start up the app and first try to hit the context (register or log in), there is an error on Database.AsRelational().ApplyMigrations() that the database already exists. However, when I connect to the database matching the connection string in config.json, I do not see the database.
"ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=aspnet-myAppDb;Trusted_Connection=True;MultipleActiveResultSets=true"
Connect to (localdb)\mssqllocaldb in SQL Server Management Studio, delete the database there. I'm not sure why this step is required or why the migrations fails, however.
There is an already accepted answer, but I prefer doing this from Visual Studio. This is caused by manually deleting the MDB file. For future reference, you should not delete the MDB files from Explorer, but instead use Visual Studio or SQL Server Management Studio to delete them.
In Visual Studio, hit Ctrl+\, Ctrl+S to bring up SQL Server Object Explorer. If your keybindings are different, look under the View Menu.
Expand the node for the type of localdb you are using, find your problem database, right click and delete. Problem fixed.

SQL Server Database is not getting attached again

I tried to detach my SQL Server 2008 R2 database for creating a duplicate of it, meanwhile connections to that database were active from Visual Studio (2010). So SQL Server denied to detach. After closing Visual Studio, I tried again and my database was successfully detached.
After detaching my database I tried to copy both files (.mdf and .ldf) to another folder as a duplicate copy, but I could not do so because I was getting error that says
You require permission from the computer administrator to make changes to this file
I am using Windows 7 and my account is Administrator. I also tried to attach my database again to SQL Server (running it with administrator permission) but I got the following error:
Failed to retrieve data for this request. (Microsoft.SqlServer.Management.Sdk.Sfc)
Additional Information:
An exception occurred while executing a Transact-Sql statement or batch.
(Microsoft.SqlServer.ConnectionInfo)
CREATE FILE encountered operating system error 5 (Access is denied,) while attempting to open or create the phyical file'C:/Mywor/MyDataBase.mdf'.
(Microsoft SQL Server, Error: 5123)
Please help me if someone know how to handle this problem.
Here are couple things you can try:
Stop SQL Server service and see if you can copy files (to stop SQL service go to SQL Server Configuration manager)
Try to copy some other database files in that directory and see if that works (make sure permissions for both files are exactly the same)
Try to copy .mdf and .ldf files in original SQL Server data directory (you can find it in SSMS -> Instance properties ->Database Settings
If you’re not using windows explorer for copying files make sure you run it as admin (right click -> Run as administrator)
This is a permissions issue on the database files directory, or the files themselves. Just because you're logged on as an administrator doesn't mean that Windows 7 allows you to do anything you want without whinging at you first. Also, the SQL Server service account may not have the appropriate permissions on the file/folder.

"This database file is not compatible with the current instance of SQL Server"

I am currently reading through a book about MVVM and I need to use the Northwind database for the next section. Unfortunately, when I try to add Northwind to my project, I get the following error:
"An error occurred while connecting to the database. The database might be unavailable. An exception of type 'Microsoft.Data.ConnectionUI.SqlDatabaseFileUpgradeRequiredException' occurred. The error message is: 'This database file is not compatible with the current instance of SQL Server.'"
I haven't installed an SQL Server, just Visual Studio 2012. The book instructs me to add the .MDF file to the project, set it as an Entity Data Model, and then to generate from database. It's on the next screen where I get the error. I use NORTHWND.MDF as the data connection and the entity connection string is as follows:
metadata=res:///Model1.csdl|res:///Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\NORTHWND.MDF;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"
In the book, this reads:
metadata=res:///Model1.csdl|res:///Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\NORTHWND.MDF;Integrated Security=True;UserInstance=True"
I have tried using both data sources and neither work.
Also of note, the sample code that goes along with the book doesn't work either. It compiles and launches, but in the server explorer, NORTHWND.MDF has an 'x' in the icon and upon launch none of the data is there.
When I attempt to upgrade the database, I get an error saying:
"Database '...\NORTHWND.MDF' cannot be upgraded because its non-release version (539) is not supported by this version of SQL Server. You cannot open a database that is incompatible with this version of sqlservr.exe. You must re-create the database..."
If anybody could give me any tips on how to get this working, I would certainly appreciate it.
my simple way:
go to VisualStadio 2012
In Server Explorer Windows
open Data Connections
Right click on ASPNETDB.MDF
click on Modify Connection...
a new windows open for you ... you just click OK
if other windows open for you click Yes
FINISH ( be Happy ) :D
If we are trying to attach .mdf file in SQL Express mode in our development project and while adding .mdf file in App_Data folder we are getting exception like below :
"The database file is not compatible with the current instance of sql server...."
Then we can go to Server explorer window → go to Data connections → go to "your database" → right click on Modify connection → check the Data sources and Database file name, then use windows Authentication and press OK.
It works for me.
one way to potentially fix it is, install Sql Server 2012 Express and use database connection to sql server. Do not use local database. That might work. Just a suggestion.
Also as an extra note, you might want to download SQL Server 2012 Management Studio (I believe it comes with the above download as a component that you have select). With Management Studio Installed, you can test the database connectivity separately, create tables, run queries etc. This will make troubleshooting a lot easier.
Visual Studio doesn't install any database server by default so you can't connect to one. The MDF file is just the file where SQL Server stores its data, it's not a standalone database.
You have to install some version of SQL Server 2012 Express for both connection strings to work.
The first connection string uses the LocalDB feature which is essentially a minimal installation of SQL Server 2012 Exrpess (~ 35 ΜΒ). You can only connect to LocalDB from your machine which makes it useful only for development purposes.
The second connection string connects to an actual instance of SQL Server Express, called SQLExpress, installed on your local machine. The second connection string attaches the MDF file to the server as a User Instance, which means that the file is released when you stop using it.
The SQL Server Express downloads range from 130 MB to 1.3 GB depending on which version you download (minimal to full with advanced services).
Northwind database is not readily compatible with 2012, the compatible version of Northwind database for sql server 2012 can be downloaded from the below link, and after downloading .mdf file we can easily attach it with sql server 2012. I have found the following and it helped me, hope it will help you. How to Attach Northwind Database in Sql Server 2012
First go to data connection as on pic:1
2.Then browser your mdf file press ok and it will automatically convert the database.
picture:01
picture:02
Modify connection may solves the problem, but I am not sure whether the type of this database file is changed.
I have found a way to solve this problem if you have installed the database Server corresponding to the database file. You just need to change the default database Server of your visual studio.
On the menu, choose Tools-> Options -> Database tools, then on the data connections enter the SQL server Instance name corresponding to your database file which you have installed,then press Ok.
Next step is also important, it is necessary to click 'refresh' or delete the database filename in Data Connection and reopen the file, the file will be added to Data Connection again and open successfully.
This is what worked for me:
On the Add Connection dialog box, click Advanced.
Scroll down to the bottom and look for a field called Data Source.
Change it from (localdb)\MSSQLlocalDB to .\SQLEXPRESS.

SQL Server Express unable to attach or delete mdf file

My database file Whist.mdf was attached to a SQL Server Express through Management Studio, but it stopped working in that sense that NHibernate in my asp.net solution fired some connection exceptions. I just detached it from Management Studio because I couldn't open the database in there either.
But when I try to reattach it I get this error:
Attach database failed for Server 'MyPCName\SQLECPRESS'. (Microsoft.SqlServer.Smo) Unable to open the physical file "C:\Program
Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\Whist.mdf".
Operating system error 32: "32(process cannot access the file because
it is being used by another process)". (Microsoft SQL Server, Error:
5120)
I have googled it but can't find a solution that works for me. E.g.:
http://www.byteblocks.com/post/2010/01/06/Unable-to-open-the-physical-file-Microsoft-SQL-Server.aspx
"Cannot open user default database. Login failed." after installing SQL Server Management Studio Express
There is something about User Instance but I cant figure out if it have anything to do with that:
http://blogs.msdn.com/b/sqlexpress/archive/2006/11/22/connecting-to-sql-express-user-instances-in-management-studio.aspx
I have tried to delete the mdf file in windows but I can't do that either:
The action can't be completed because the file is open in system
I have tried stopping the SQL Server process, closing explore and delete from cmd and rebooting...
Hope someone can help - I guess it is just a simple thing..
I think you are on the right track. The error messages you are getting indicate that some SQL Server process is keeping the database file open. And SQL Server is designed to only allow the database file to be open by a single SQL Server process at a time.
You are also probably right to suspect User Instance of SQL Server Express to be the guilty process here. User Instance is a special SQL Server process that doesn't run as a service and instead is started and owned by the application that tries to connect to it. In your case there are two User Instances that can be the problem, one owned by the ASP.NET application you mentioned and one owned by you and started by Visual Studio. If you are using IIS Express or you configured the IIS App Pool for the ASP.NET application to run as your account then we only have one User Instance to worry about.
My recommendation is that you don't use User Instances and don't try to connect directly to the database file. Go over your connection strings and remove User Instance=true from all of them. You want to remove AttachDBFilename=... property as well.
If the database file is added to any of your Visual Studio solutions remove it (just be careful not to delete the file itself). The last step is to remove any connections to the database file from your Data Connections node in the Server Explorer.
Then restart the machine to make sure any User Instances that were running in the background were shutdown. After the machine starts again you should be able to attach the database file back to your main SQL Server Express using SQL Server Management studio. Let's name the database Whist
To connect to your database use the following connection string:
Data Source=.\SQLExpress;Integrated Security=true;Initial Catalog=Whist
When you connect from the ASP.NET application, make sure that you have created an account in your SQL Server Express for the application.
Turned out to be an issue with Daemon tools for me as well associating the .mdf file as an image.
If you want to copy your .mdf and .ldf file from your database, you can set your database file to 'offline' first . Please follow this steps:
Open your SQL Server 2008(suppose you are using SQL Server 2008 ).
Select your Database that you want to copy then left click.
Go to Tasks -> Take Offline.
Right click.
Then you can copy this database file to any folders.

Using Web Deploy (msdeploy) to publish a WebMatrix site

I started building my site in WebMatrix and then switched to using VS2010 so I could have better Intellisense and debugging. I've been loading WebMatrix to deploy and it's been working fine.
However, loading WebMatrix is a PITA and I actually want more flexibility over the web deployment process.
So I started learning about msdeploy.exe and how to use it. I was able to successfully get the site to sync as I wanted with the following command line:
msdeploy.exe
-verb:sync
-dest:iisApp=MySite,wmsvc=www.mysite.com,username=administrator,password=blahblahblah
-allowUntrusted
-skip:absolutePath=webdeploy.cmd
-skip:absolutePath=web.config
-skip:objectName=dirPath,absolutePath="App_Data"
-skip:objectName=dirPath,absolutePath="bin"
-skip:absolutePath=vwd.webinfo
-source:iisApp="C:\Users\charlie\Documents\Visual Studio 2010\WebSites\MySite"
I had to use -allowTrusted because the cert on the server uses a differnt host name than www. No biggie. I have some -skips for stuff I don't want to write to the dest as well.
It all works great.
I use SQL Server (Express) on my host (a WebMatrix AMI on AWS).
I want to have the ability to push my database to the host as well. I am trying to use the following msdeploy commmand:
msdeploy.exe
-verb:sync
-source:dbFullSql="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=C:....\MySite.mdf;User instance=true"
-dest:dbFullSql="Server=www.mysite.com\SQLEXPRESS;Initial Catalog=webmatrix_db;Uid=webmatrix_user;Pwd=<pwd>"
This gives me
Error: The database 'webmatrix_db' could not be created.
Error: A network-related or instance-specific error occurred while establishing aa
connection to SQL Server. The server was not found or was not accessible. ...
I think my problem is the connection string. I copied Server=".\SQLEXPRESS;Initial Catalog=webmatrix_db;Uid=webmatrix_user;Pwd=<pwd> from the WebMatrix UI and pre-pended it with www.mysite.com thinking it needed my hostname somewhere.
Obviously this is not correct and I can't find any examples of connection strings that work either.
Note that SQL is not exposed directly by this server. I assume WebMatrix's invocation of msdeploy is connecting using my admin credentials (not the SQL credentials) first and then msdeploy invokes the SQL commands on the remote host. I need something like the ...wmsvc=www.mysite.com,username=administrator,password=blahblahblah in the -dest option of the first example I gave above.
It would be awesome if I could see a log of how WebMatrix was invoking msdeploy.
What is the correct msdeploy command to do what I want?
[UPDATE - ANSWER]
One of the best things about StackOverflow, is that posting a question really makes you think about what you are doing. Shortly after I posted the above, I realized the wmsvc=www.mysite.com,username=administrator,password=blahblahblah parameter in the -dest parameter was the key. The question became how to correctly add it to my specific example.
This msdeploy command line now connects correctly:
msdeploy.exe -verb:sync -source:dbFullSql="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=C:\Users\charlie\Documents\Visual Studio 2010\WebSites\Fiinom\App_Data\MySite.mdf;User instance=true" -dest:dbFullSql="Server=.\SQLEXPRESS;Initial Catalog=webmatrix_db;Uid=webmatrix_user; Pwd=rI2vP3rK6hV8nN8",wmsvc=www.mysite.com,username=administrator,password=blahblahblah -allowUntrusted
Now that msdeploy is connecting successfully and executing commands, I need to figure out how to make it actually merge the database. Right now it's giving me an error that a table already exists and can't create it...
This is related to your side comment on merging the database...
Currently Web Deploy does not have any provider that supports database merges - the dbFullSql provider uses SQL Server Management Objects ("SMO") to script out the db contents and we then apply it on the other side. Effectively Web Deploy thus will only overwrite the destination db with the source db.
If you are okay with that as a "merge" you can get around that table already exists error by using SMO scripting options - this is what WebMatrix does to make the db publishing/downloading work. To your source just add:
,scriptDropsFirst=true
(this scripts out drops for all the objects in your source database so that if they exist on the destination they will get dropped and won't block you)
You might also need:
,copyAllUsers=false
(if you aren't a sysadmin on the remote SQL database, chances are you won't be able to create logins, which are a server-level action. Typically if you don't use this setting, you'll get an error about creating a login, or login doesn't exist, because SMO scripts our your database user as "for LOGIN " and that login doesn't exist on the server)
Hope that helps!
Kristina