An attempt to attach an auto-named database for file ....database1.mdf failed

Solution 1:

I had this problem also and it was a pain. I configured my connection string and managed to solve the problem. In the connection string I replaced the value |DataDirectory|\dbfilename.mdf for AttachDbFilename property, with the path to the file. |DataDirectory| can only be used if the database file is in the App_Data folder inside same project.

So changing the AttachDbFilename property to the direct path of the mdf file, fixed my issue.

AttachDbFilename=C:\MyApp\App\DAL\db.mdf

I hope this works for you.

Solution 2:

Try to create your connection string as below:

 <add name="ECommerce" connectionString="Data Source=(localdb)\v11.0;Initial Catalog=C:\USERS\dL\DESKTOP\DATABASE\MYSHOP.MDF;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False" providerName="System.Data.SqlClient"/>

It's working for me.

Solution 3:

<add name="Connections" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>

Solution 4:

I had a similar error, but using a connection configured in code, rather than a config file. The solution for me was simply to add the "Initial Catalog=MyDatabase" part. My code now looks like...

DbConnection connection = new SqlConnection(String.Format(@"Data Source=.\SQLEXPRESS; Integrated Security=SSPI; AttachDbFilename={0}; User Instance=True; Initial Catalog=IPDatabase;", Location));

Location is a full path to an mdb file, that does not have to exist yet.