Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot connect to .mdf database

Tags:

c#

sql

asp.net

I've tried everything but I can not access/change/modify my database. I created it in visual studio with .mdf. I am new at using SQL database so I will be glad if you can help me. As I said, I created that database, in visual studio but I can not create a connection with that database.

In web config :

<connectionStrings>
   <add name="ConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDBFilename=|DataDirectory|Database.mdf;Integrated Security=True;"
      providerName="System.Data.SqlClient" />
  </connectionStrings>

In cs I used that sql connection string:

SqlConnection conn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDBFilename=|DataDirectory|Database.mdf;Integrated Security=True;");

And I have this error:

An attempt to attach an auto-named database for file C:\Users\mcan\Documents\Visual Studio 2010\WebSites\WebSite1\App_Data\Database.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.


I've made some changes:

In web config :

<connectionStrings>
 <add name="ConnectionString" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=|DataDirectory|Database.mdf;Integrated Security=True;"
  providerName="System.Data.SqlClient" />

and in cs:

 SqlConnection conn = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=|DataDirectory|Database.mdf;Integrated Security=True;");

Now it gives that error:

*Server Error in '/WebSite1' Application. Cannot open database |DataDirectory|Database.mdf" requested by the login. The login failed. Login failed for user 'mcan-PC\mcan'. *
like image 758
Mert Yigin Avatar asked Feb 02 '12 16:02

Mert Yigin


2 Answers

As the error clearly states, that database is already connected to SQL Server.
You can't have two databases with the same name on the same server.

like image 94
SLaks Avatar answered Nov 09 '22 14:11

SLaks


The problem could be that your mdf file doesn't have permissions set for Authenticated Users. Navigate to your .mdf file, right click and go to Properties then the Security tab. Check if the Authenticated Users appears in 'Group or user names'. If it doesn't then you'll have to click on Edit then Add and type in Authenticated Users. Then you'll hit Check names and OK. After that enable full control for Authenticated Users. You'll have to repeat this for the .ldf file too.

like image 25
huel Avatar answered Nov 09 '22 15:11

huel