Tuesday, October 27, 2015

Database login error in Visual Studio

Error:
Cannot open user default database. Login failed.
Login failed for user 'abcxyz'.

I got this error in my Visual Web Developer 2010 Express.

My database named Database1.mdf was not opening and throwing this error.

Solution:
1. Right click on App_Data folder and select Add > Existing Item.
2. Browse to your solution directory and select the database for which you are getting this error. In my case it was Database1.mdf.
3. Add that database and rename it. I renamed newly added database to Database.mdf.
4. Remove older database.
5. Open Web.config file and edit the new database name:

change connection string from below

connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True"

change it to below

connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True"