SqlException:System.Data.SqlClient [duplicate] - c#

I have created a web service which is saving some data into to db. But I am getting this error:
Cannot open database "test" requested by the login. The login failed. Login failed for user 'xyz\ASPNET'.
My connection string is
Data Source=.\SQLExpress;Initial Catalog=IFItest;Integrated Security=True

Well, the error is pretty clear, no? You are trying to connect to your SQL Server with user "xyz/ASPNET" - that's the account your ASP.NET app is running under.
This account is not allowed to connect to SQL Server - either create a login on SQL Server for that account, or then specify another valid SQL Server account in your connection string.
Can you show us your connection string (by updating your original question)?
UPDATE: Ok, you're using integrated Windows authentication --> you need to create a SQL Server login for "xyz\ASPNET" on your SQL Server - or change your connection string to something like:
connectionString="Server=.\SQLExpress;Database=IFItest;User ID=xyz;pwd=top$secret"
If you have a user "xyz" with a password of "top$secret" in your database.

Either: "xyz\ASPNET" is not a login (in sys.server_principals)
Or: "xyz\ASPNET" is set up but not mapped to a user in the database test (sys.database_principals)
I'd go for the 2nd option: the error message implies the default database is either not there or no rights in it, rather than not set up as a login.
To test if it's set up as a login
SELECT SUSER_ID('xyz\ASPNET') -- (**not** SUSER_SID)
If NULL
CREATE LOGIN [xyz\ASPNET] FROM WINDOWS
If not NULL
USE test
GO
SELECT USER_ID('xyz\ASPNET')
If NULL
USE test
GO
CREATE USER [xyz\ASPNET] FROM LOGIN [xyz\ASPNET]

I had this problem and what solved it for me was to:
Go to the Application pools in the IIS
Right click on my project application pool
In Process Model section open Identity
Choose Custom account option
Enter your pc user name and password.

For me the database was not created and EF code first should have created it but always endet in this error. The same connection string was working in aspnet core default web project. The solution was to add
_dbContext.Database.EnsureCreated()
before the first database contact (before DB seeding).

The best solution for the login problem is to create a login user in sqlServer. Here are the steps to create a SQL Server login that uses Windows Authentication (SQL Server Management Studio):
In SQL Server Management Studio, open Object Explorer and expand the folder of
the server instance in which to create the new login.
Right-click the Security folder, point to New, and then click Login.
On the General page, enter the name of a Windows user in the Login name box.
Select Windows Authentication.
Click OK.
For example, if the user name is xyz\ASPNET, then enter this name into Login name Box.
Also you need to change the User mapping to allow access to the Database which you want to access.

Most times, it's not a login issue, but an issue with creating the database itself. So if there is an error creating your database, it would not be created in the first place. In which case if you tried to log in, regardless of the user, login would fail. This usually happens due to logical misinterpretation of the db context.
Visit the site in a browser and REALLY read those error logs, this can help you spot the problem with you code (usually conflicting logic problems with the model).
In my case, the code compiled fine, same login problem, while I was still downloading management studio, I went through the error log, fixed my db context constraints and site started running fine....meanwhile management studio is still downloading

This Works for me.
Go to SQL Server >> Security >> Logins and right click on NT AUTHORITY\NETWORK SERVICE and select Properties
In newly opened screen of Login Properties, go to the “User Mapping” tab.
Then, on the “User Mapping” tab, select the desired database – especially the database for which this error message is displayed.
Click OK.
Read this blog.
http://blog.sqlauthority.com/2009/08/20/sql-server-fix-error-cannot-open-database-requested-by-the-login-the-login-failed-login-failed-for-user-nt-authoritynetwork-service/

It also happen when you type wrong name of DB
ex : xxx-db-dev to xxx-dev-db
Sometime, it's just a stupid mistake . I take about more than 1 hours to find out this :( because i just try alot of difficult thing first

The Issue
The error presents itself as a message similar to this:
Cannot open database "DATABASE NAME" requested by the login. The login
failed. Login failed for user XYZ.
The error cannot usually be rectified by a simple Visual Studio or full-computer restart.
The error can also be found as a seemingly locked database file.
The Fix
The solution is laid in the following steps. You will not lose any data in your database and you should not delete your database file!
Pre-requisite: You must have installed SQL Server Management Studio (Full or Express)
Open SQL Server Management Studio
In the "Connect to Server" window (File->Connect object explorer) enter the following:
Server type : Database Engine
Server name : (localdb)\v11.0
Authentication : [Whatever you used when you created your local db. Probably Windows Authentication).
Click "Connect"
Expand the "Databases" folder in the Object Explorer (View->Object Explorer, F8)
Find your database. It should be named as the full path to your database (.mdf) file
You should see it says "(Pending Recovery)" at the end of the database name or when you try to expand the database it won't be able to and may or may not give you an error message.
This the issue! Your database has crashed essentially..
Right click on the database then select "Tasks -> Detach...".
In the detach window, select your database in the list and check the column that says "Drop Connections"
Click OK.
You should see the database disappear from the list of databases. Your problem should now be fixed. Go and run your application that uses your localdb.
After running your application, your database will re-appear in the list of databases - this is correct. It should not say "Pending recovery" any more since it should be working properly.
The source of the solution: https://www.codeproject.com/Tips/775607/How-to-fix-LocalDB-Requested-Login-failed

I tried to update the user, and it worked. See the command below.
USE ComparisonData// databaseName
EXEC sp_change_users_login #Action='update_one', #UserNamePattern='ftool',#LoginName='ftool';
Just replace user('ftool') accordingly.

I had this problem when I created a WPF .NET Core + Entity Framework Core project and then cloning it on a a new laptop.
Using:
update-database
in the package manager console simply solved it.
To open package manager console go to:
Tools-> Nuget Package Manager -> Package Manager console

I used Windows authentication to connect to local database .mdf file and
my local server was sql server 2014.
My problem solved using this connection string:
string sqlString = " Data Source = (LocalDB)\\MSSQLLocalDB;" + "AttachDbFilename = F:\\.........\\myDatabase.mdf; Integrated Security = True; Connect Timeout = 30";

In my case it is a different issue. The database turned into single user mode and a second connection to the database was showing this exception.
To resolve this issue follow below steps.
Make sure the object explorer is pointed to a system database like master.
Execute a exec sp_who2 and find all the connections to database ‘my_db’. Kill all the connections by doing KILL { session id } where session id is the SPID listed by sp_who2.
USE MASTER;
EXEC sp_who2
Alter the database
USE MASTER;
ALTER DATABASE [my_db] SET MULTI_USER
GO

I ran into this issue when attempting to write to the default database provided in the asp.net mvc template. This was due to the fact that the database hadn't been created yet.
To create the database and make sure that it is accessible follow these steps:
Open up the Package manager console in Visual Studio
Run the command "update-database"
This will create the database an run all the necessary migrations on it.

I have not seen this mentioned in the previous issues, so let me throw out another possibility. It could be that IFItest is not reachable or simply does not exist. For example, if one has a number of configurations, each with its own database, it could be that the database name was not changed to the correct one for the current configuration.

NB: If using a windows service to host the webservice.
You have to insure that your webservice is using the right Log on account to connect to SQL Server.
Open services(I assume the windows service has been install)
Right click on the service and goto properties.
Click on "Log On" Tab
Click on "This account" radio button
Click "Browse"
Enter Pc user name in Text Field and click "Check Name" Button to the right.
Click on text in Text Field, press "OK" button
enter login password and Apply

Inspired by cyptus's answer I used
_dbContext.Database.CreateIfNotExists();
on EF6 before the first database contact (before DB seeding).

If you haven't created the database in your server you will get the same login error.Make sure that the database exist before you login.

it's not a login issue most times. The database might not have been created. To create the database, Go to db context file and add this.Database.EnsureCreated();

The best option would be to use Windows integrated authentication as it is more secure than sql authentication. Create a new windows user in sql server with necessary permissions and change IIS user in the application pool security settings.

I found that I also had to set the UserMapping option when creating a new login and this solved the problem for me. Hope that helps anyone that also found themselves stuck here!
Edit: Setting the login as db owner solved the next problem, too

Some times this trouble may appear if you open this db in another sql server (as example, you launch sql managment studio(SMS) and add this db), and forget stop this server. As result - you app try to connect with user already connected in this db under another server. To fix that, try stop this server by Config. dispatcher sql server.
My apologies about bad english.
Kind regards, Ignat.

In my case the asp.net application can usually connect to database without any problems. I noticed such message in logs. I turn on the SQL server logs and I find out this message:
2016-10-28 10:27:10.86 Logon Login failed for user '****'. Reason: Failed to open the explicitly specified database '****'. [CLIENT: <local machine>]
2016-10-28 10:27:13.22 Server SQL Server is terminating because of a system shutdown. This is an informational message only. No user action is required.
So it seems that server was restarting and that SQL server whad been shutting down a bit earlier then ASP.NET application and the database was not available for few seconds before server restart.

Even if you've set the login as DB owner and set the user mapping for the database that will use the login, check that the actual DB user (not just the login) has the role of 'owner'.

In my case, I was running a Windows Service under "System" identity. The error was:
System.Data.SqlClient.SqlException (0x80131904):
Cannot open database "MyDbName" requested by the login. The login failed.
Login failed for user 'MYDOMAINNAME\HOSTNAME$'.
The problem is that the error is very misleading. Even after I added 'MYDOMAINNAME\HOSTNAME$' login to the database, and granted this login sysadmin access and added a user for that login on my target database, and made that user dbowner, I was still getting the same error.
Apparently I needed to do the same for 'NT AUTHORITY\SYSTEM' login. After I did that, I was able to login without a problem. I don't know why the error message complains about 'MYDOMAINNAME\HOSTNAME$'. I deleted that login and the corresponding user and everything still works.

When using EF Code First, make sure the database exists. You could run the update-database command first.

If none of the above solution is working.
I encountered with the same error message but my issue was completely different. I had just restore my database and the database was in restoring mode. So if your database is in rstoring mode just apply following query.
RESTORE DATABASE MyDatabase
FROM DISK = 'pathToYourDbBackup\MyDatabase.bak'
WITH REPLACE,RECOVERY

I had this happen to me when I deleted the DB and forgot to recreate it. It happens sometimes, since Database folder needs refresh.

If you didn't have any problems before and you get this error only in the package manager console, you don't need to do anything special. Just open the sql server object explorer window and connect and run the command again in the console.

Related

C# MySql error: MySql.Data.MySqlClient.MySqlException [duplicate]

Trying to connect to MySQL on my web host, using Connector/Net C#/WinForms in Visual Studio 2012 Update 3, but getting the below error message:
Authentication to host '1.1.1.1' for user 'username#mydomain.com' using method 'mysql_native_password' failed with message: Access denied for user 'username#mydomain.com'#'2.2.2.2' (using password: YES)
string connectionString = "SERVER=1.1.1.1;PORT=3306;DATABASE=databaseName;UID=username#mydomain.com;PASSWORD=mypassword;";
MySqlConnection connection = new MySqlConnection(connectionString);
connection.Open();
I am connecting remotely, have whitelisted my IP (and even temporary whitelisted all (%) to test), triple checked the username and password and IP.
I originally tried the username without the domain ( username rather than username#mydomain.com) but it gave me the below error:
Authentication with old password no longer supported, use 4.1 style passwords.
Any assistance would be much appreciated, thanks!
Its problem of 'Remote Database Access Hosts'.
"You can allow external web servers to access your MySQL databases by adding their domain name to the list of hosts that are able to access databases on your web site."
MySql access is not granted to IP address of the system at which application is running.(in your case its '2.2.2.2' ).
Note:- '2.2.2.2' is your public IP address.
Two possible things:
MySQL is case sensitive make sure that the case of Database= in your connection string matches with the actual database name
You may have to grant privileges to the user.
I hope this help you.
Check your application settings file (or wherever you have stored the connection string).
In my case the application was using the old connection string (which was not valid). I was assuming that the change I made in the code of the settings file is reflected to the designer (of the settings file). But it was not!
After creating a new user in MySQL, in MySQL Workbench "Test Connection" will succeed but the C# MySqlConnection.Open() will throw the same exception and message as the question (tested with localhost and 127.0.0.1 and the local ip address).
The reason is that MySqlConnection.Open() will somehow use SELECT privilege, and you need to at least enable the SELECT privilege for the new user. The error message is misleading.
This might be related to the case of specific Membership SQL Server based instructions on ASP.NET 4.5, workaround is to create new membership in web.config, drop mvc 4 AccountControler and use old from MVC3 more here or in the internet:
http://www.nsilverbullet.net/2012/11/06/using-mysql5-as-membership-backend-for-aspnet45-mvc4-application/
In my case updated password was not used. I just generated the password using Password Generator and copy it but forgot to click Change Password.
Also check the user is added to the database and has Privileges.
For me, using the actual IP address instead of the domain name solved the problem
While Whitelisting my Ip on cpanel i had accidentally put a space in there after my ip address.[Should have been handled by them]
I added the ip again and it worked.
In my case, the problem was misleading as well.
Had quite a few windows terminals running "the same" .net app all connecting to a remote MySQL server (installed in a windows server machine). However, only one always popping the specific error when anyone clicked to run the .net application. ODBC test connection passed successfully, and no matter if the error popped, when presing OK the application continued loading successfully finally and then worked fine.But again afterwards , when anyone tried to run in for the first time the message appeared. and I repeat only in this specific terminal! The fix finally came when I noticed, that it was only in this specific terminal with the problem that we had forgotten DHCP enabled! and "although it was given always the same IP" from our IT policies, however it only worked when we disabled DHCP and set this IP, SUBNET and GW, as fixed !
Check with a program like Navicat that the mysql server user has a native password. Everything is correct but if you are getting this error check the version of the link DLL
This error; Mysql.Data.dll and Mysql Server version mismatch error. Download and install an older version
https://downloads.mysql.com/archives/c-net/
Mysql Version < 4.5
Mysql.Data.Dll version= 6.0.3

Azure Mobile Service login error with database and "master" user

I've been using Azure Mobile Services with my apps without much issue, but then today when I tried to pull from the service I get this error:
Exception=System.Data.SqlClient.SqlException (0x80131904): Cannot open
database "master" requested by the login. The login failed. Login
failed for user 'JVlSvKwDpdLogin_*****'.
I've never had this issue come up before, and I'm only connecting to my mobile service in code like this:
public static MobileServiceClient MobileService = new MobileServiceClient(
"https://<webservicename>.azure-mobile.net/",
"<YOUR-API-KEY-HERE>"
);
Before this error happened, I never supplied a username or password. I've seen some solutions where they've created a user for the database but I don't want to create one right now since we're still in testing and I'd rather be able to use the service without one for now. Is this an issue with mobile service, or an issue with the database?
UPDATE
As suggested by Matt's answer below, I found the MS_ConnectionString in the Azure portal. I then connected to the 'master' database on my Azure SQL server and searched for the login above. I changed the password to the one found in the connection string using
ALTER LOGIN <login> WITH password='<password-found-in-connection-string>';
But now I get this error:
Exception=System.Data.Entity.Core.ProviderIncompatibleException: An error occurred accessing the database. This usually means that the connection to the database failed. Check that the connection string is correct and that the appropriate DbContext constructor is being used to specify it or find it in the application's config file. See http://go.microsoft.com/fwlink/?LinkId=386386 for information on DbContext and connections. See the inner exception for details of the failure. ---> System.Data.Entity.Core.ProviderIncompatibleException: The provider did not return a ProviderManifestToken string. ---> System.Data.SqlClient.SqlException: Login failed for user 'JVlSvKwDpdLogin_*******'.
I haven't change anything with the connection string or the web.config file for my AzureMobileService project.
web.config:
<connectionStrings>
<add name="MS_TableConnectionString" connectionString="Data Source= (localdb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-CoverageTool.AzureMobileService-20140910083006.mdf;Initial Catalog=aspnet-CoverageTool.AzureMobileService-20140910083006;Integrated Security=True;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
</connectionStrings>
MobileContext:
private const string connectionStringName = "Name=MS_TableConnectionString";
public MobileServiceContext()
: base(connectionStringName)
{
}
Connection String
Data Source=*****.database.windows.net;Initial Catalog=sbpconsulting_db;User ID=*******Login_sbpconsulting;Password=**************;Asynchronous Processing=True;TrustServerCertificate=False;
This error could also appear if your Entity Framework database initializers are not compatible with the permissions of the database user that your Azure Mobile Service is using.
For example, when you create database for a Azure Mobile Service, Azure automatically creates a DB user for your service. This user does not have admin permissions - it can generally read and write data to a table. In that case, if you are using DropCreateDatabaseAlways DB initializer your user will not have sufficient permission to actually drop the database and you may see the error that you have mentioned.
There are new initializers that were introduced to work with limited set of permissions:
ClearDatabaseSchemaAlways - use instead of DropCreateDatabaseAlways
ClearDatabaseSchemaIfModelChanges - use instead of DropCreateDatabaseIfModelChanges
I can only think of one thing that may be the problem. Windows Azure Databases only allow specific ip addresses that you have white listed before hand.
So if you are trying to run your app from a different internet connection or if your ip address has changed then that might be your issue.
Try accessing your database directly on your Azure Management Console and allow your ip address access to the database server.
Azure always needs authentication so check your applications app.config / web.config file for credentials.
More code-based information would have been helpful to make this answer more than a shot in the dark.
Do you control the SQL login? Do you have other databases hosted on the same SQL Azure server?
That error is happening on the backend between your service tier and the database and won't be impacted by anything in the client application(s).
The account setup in the portal doesn't have the permissions it needs. Either you have found a bug, someone has revoked the permissions for that user, or the password has changed.
Based on the error message, I'd say it is the latter issue and you need to find out what the password is and make sure it is in sync with the MS_TableConnectionString setting on the Configure tab of your mobile service. You might have to reset the password for that login on SQL and also update the connection string just to make sure they are the same.
Another thing that may be a problem is EF migrations. Have you changed your model and enabled migrations? This would all run fine on your local instance and you could add migrations and update database. When you go to deploy though you'd want to enable automatic migrations to make sure the SQL Azure DB also gets the migrations applied. I've seen people have issues with this same error message (ProviderIncompatible) when it was a migrations issue.
To enable auto migrations make sure you go into the configuration.cs file and change the line of code that sets boolean property to "false" by default to "true".
I also had this issue.
My Mobile Service was connecting to my Azure SQL Database called 'Diary'. This was working ok for a few weeks. Then, without any changes from my side , I started getting the error :
Exception=System.Data.SqlClient.SqlException (0x80131904): Cannot open database "master" requested by the login. The login failed. Login failed for user 'HwRkAPcQLyLogin_xxxService'.
I fixed the issue by:
adding the user 'HwRkAPcQLyLogin_xxxService' to my 'Diary' database
assigning db_owner permissions to the 'HwRkAPcQLyLogin_xxxService' user
I used this handy tool to manage the Azure Users:
https://aumc.codeplex.com/
I did not have to change anything in the master database.

First chance exception of 'System.Data.EntityException'. The underlying provider failed on Open

I've been given a site that was created by someone else and I'm now trying to test it. I can compile the system without any problems but when I try to log in to the website, I get the error:
"EntityException occured. A first chance exception of type 'System.Data.EntityException' occured in System.Data.Entity.dll. Additional info: The underlying provider failed on Open."
Furthermore, if I dig deeper, I see an InnerException of Cannot open database \"MyDB\" requested by the login. The login failed. Login failed for user 'name\\owner'.
I've read similar problems on the web and it seems like its a problem with database connections? I've tried multiple 'solutions' that include messing around with the connectionString but nothing works.
What I think the system wants to do is connect to a .mdf located in a separate project's App_Data. Anyway, here's the connectionString code that I received originally:
add name="NameServiceContext"
connectionString="Server=tcp:qiu5vg5yhv.database.windows.net,1433;Database=MyDB;User ID=MYID;Password=MYPASS;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;"
providerName="System.Data.SqlClient"
Quick question, what is the tcp:...... stuff? I'm assuming it was generated somehow, but how?
I've tried 'fixing' the problem and ended up with something like this:
add name="NameServiceContext"
connectionString="data source=./SQLEXPRESS;AttachDbFilename=C:\Users\owner\Documents\MyERP\App_Data\MyDB.mdf;Integrated Security=True;Connect Timeout=30;"
providerName="System.Data.SqlClient"
Both methods give the same errors and I'm out of ideas. How would I go about fixing this?
Also, when I connect to a db via tools>connect to database > MS SQL db file, I get an option between 2 data sources, ./SQLEXPRESS and (LocalDB)\v11.0. Do I have to include both of them? If so, how?
The original connection string refers to a Microsoft Azure instance. A typical connection string to Azure looks like:
Server=tcp:[serverName].database.windows.net;Database=myDataBase;User ID=[LoginForDb]#[serverName];Password=myPassword;Trusted_Connection=False;Encrypt=True;
Your server name is qiu5vg5yhv.database.windows.net. Most likely your credentials are incorrect.
It is as Andrew said, you don't seem to have access to the actual database. Simply download either "SQL Server Management Studio" or "SQL Server Management Studio Express" (depend on which version of database you are using) and try to connect.
If you connect successfully, check if you can query the database of your project.
If you connect unsuccessfully, contact your system admin to arrange access.
If you want to understand more about connectionstring or create one, use the following site for template: http://www.connectionstrings.com/sql-server/
You can get the necessary database details by viewing the Properties of your database via "SQL Server Management Studio" (right click and select Properties --> View Connection Properties)
I met the same question. The key step is here.
I used vs 2013 update 4.
When you configured your SQL in azure, it generated a connect string.

IIS APPPOOL\MyAppPool unable to log in to my SQL Server database

I've got a local WCF web service project that I'm trying to get to access my database. This is my setup:
SQLServer 2008 R2 Express
IIS 7.5
Using IIS APPPOOL\MyAppPool application pool
The AppPool is set to target .Net 4.0 and its identity is set to ApplicationPoolIdentity.
The AppPool user is added in the database and has been assigned dataReader and dataWriter rights. I've tried adding the user to the database both as a "Login" under Security\Logins and as a user under MyDatabase\Security\Users.
Since I'll eventually switch to sql server authentication, I also tried using a real windows user that I assigned reader/writer rights in the database.
I then tried converting the ApplicationPool's identity to NetworkService and added the NT AUTHORITY\NETWORK SERVICE user to the DB aswell but with equal lack of success.
This is the connection string that I'm currently using (With integrated security):
Server=.\SQLEXPRESS;Database=MyDatabase;Integrated Security=true"
As soon as I try to interact with the database in my web service code I get this error:
System.Data.SqlClient.SqlException: Cannot open database "MyDatabase" requested by the login. The login failed. Login failed
for user 'IIS APPPOOL\MyAppPool'.
When using other users than the ApplicationPool then their user names are displayed instead of the IIS APPPOOL one.
Does anyone have any idea what I could've missed?
UPDATE:
With some help from Oded and Tomek I'm now pretty sure that it has to do with the SQL Server. When using SQL Server Authentication I get this error (In the windows event log)
Reason: An attempt to login using SQL authentication failed. Server is configured for Windows authentication only.>
Using Integrated Security (IIS APPPOOL\MyAppPool user) I get this error in the event log
Reason: Failed to open the explicitly specified database.
The server is configured to use "SQL Server and Windows Authentication mode" though which puzzles me. It seems like the second message simply means that the credentials were wrong, which also seems weird since the AppPool user does not have a password. Using the script posted by guptam in post 6 here: http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=121202 does NOT show my IISAPPPOOL user nor the one created for SQLServer Authentication. The users do exist under both Login and Users and they have the correct rights assigned.
The connection string should be:
"Server=.\SQLEXPRESS;Database=MyDatabase;Integrated Security=SSPI;"
The value for Integrated Security is SSPI, not True.
There is an alternative syntax:
"Server=.\SQLEXPRESS;Database=MyDatabase;Trusted_Connection=True;"
The key here is Trusted_Connection, not Integrated Security.
I suggest taking a look at connectionstrings.com - a good resource for correct connection strings.
Go to your IIS Manager -> ApplicationPool. Right Click your website ApplicationPool and chose Advance Settings. And change Identity to LocalSystem.
Reference
Can you try these steps (some steps of your description are a bit unclear). Let's try to use "sql server authentication"
Create Login Security->Logins, mark "sql server authentication", provide password, untick "user mast change password at next login"
Select "default database" to the one you use
Go to "User Mapping" page and select your database
Use below connection string with user you just configured
connectionString="Data Source=YourDbServerName;Initial Catalog=YourDbName;User ID=YourLogin;Password=YourPass"
I eventually decided to reinstall SSMS and to recreate my database from scratch. It's now up and running as it should. I must've had something fundamentally wrong in some basic setting. Sry for all the confusion and thx for all the help!

Cannot open database "test" requested by the login. The login failed. Login failed for user 'xyz\ASPNET'

I have created a web service which is saving some data into to db. But I am getting this error:
Cannot open database "test" requested by the login. The login failed. Login failed for user 'xyz\ASPNET'.
My connection string is
Data Source=.\SQLExpress;Initial Catalog=IFItest;Integrated Security=True
Well, the error is pretty clear, no? You are trying to connect to your SQL Server with user "xyz/ASPNET" - that's the account your ASP.NET app is running under.
This account is not allowed to connect to SQL Server - either create a login on SQL Server for that account, or then specify another valid SQL Server account in your connection string.
Can you show us your connection string (by updating your original question)?
UPDATE: Ok, you're using integrated Windows authentication --> you need to create a SQL Server login for "xyz\ASPNET" on your SQL Server - or change your connection string to something like:
connectionString="Server=.\SQLExpress;Database=IFItest;User ID=xyz;pwd=top$secret"
If you have a user "xyz" with a password of "top$secret" in your database.
Either: "xyz\ASPNET" is not a login (in sys.server_principals)
Or: "xyz\ASPNET" is set up but not mapped to a user in the database test (sys.database_principals)
I'd go for the 2nd option: the error message implies the default database is either not there or no rights in it, rather than not set up as a login.
To test if it's set up as a login
SELECT SUSER_ID('xyz\ASPNET') -- (**not** SUSER_SID)
If NULL
CREATE LOGIN [xyz\ASPNET] FROM WINDOWS
If not NULL
USE test
GO
SELECT USER_ID('xyz\ASPNET')
If NULL
USE test
GO
CREATE USER [xyz\ASPNET] FROM LOGIN [xyz\ASPNET]
I had this problem and what solved it for me was to:
Go to the Application pools in the IIS
Right click on my project application pool
In Process Model section open Identity
Choose Custom account option
Enter your pc user name and password.
For me the database was not created and EF code first should have created it but always endet in this error. The same connection string was working in aspnet core default web project. The solution was to add
_dbContext.Database.EnsureCreated()
before the first database contact (before DB seeding).
The best solution for the login problem is to create a login user in sqlServer. Here are the steps to create a SQL Server login that uses Windows Authentication (SQL Server Management Studio):
In SQL Server Management Studio, open Object Explorer and expand the folder of
the server instance in which to create the new login.
Right-click the Security folder, point to New, and then click Login.
On the General page, enter the name of a Windows user in the Login name box.
Select Windows Authentication.
Click OK.
For example, if the user name is xyz\ASPNET, then enter this name into Login name Box.
Also you need to change the User mapping to allow access to the Database which you want to access.
Most times, it's not a login issue, but an issue with creating the database itself. So if there is an error creating your database, it would not be created in the first place. In which case if you tried to log in, regardless of the user, login would fail. This usually happens due to logical misinterpretation of the db context.
Visit the site in a browser and REALLY read those error logs, this can help you spot the problem with you code (usually conflicting logic problems with the model).
In my case, the code compiled fine, same login problem, while I was still downloading management studio, I went through the error log, fixed my db context constraints and site started running fine....meanwhile management studio is still downloading
This Works for me.
Go to SQL Server >> Security >> Logins and right click on NT AUTHORITY\NETWORK SERVICE and select Properties
In newly opened screen of Login Properties, go to the “User Mapping” tab.
Then, on the “User Mapping” tab, select the desired database – especially the database for which this error message is displayed.
Click OK.
Read this blog.
http://blog.sqlauthority.com/2009/08/20/sql-server-fix-error-cannot-open-database-requested-by-the-login-the-login-failed-login-failed-for-user-nt-authoritynetwork-service/
It also happen when you type wrong name of DB
ex : xxx-db-dev to xxx-dev-db
Sometime, it's just a stupid mistake . I take about more than 1 hours to find out this :( because i just try alot of difficult thing first
The Issue
The error presents itself as a message similar to this:
Cannot open database "DATABASE NAME" requested by the login. The login
failed. Login failed for user XYZ.
The error cannot usually be rectified by a simple Visual Studio or full-computer restart.
The error can also be found as a seemingly locked database file.
The Fix
The solution is laid in the following steps. You will not lose any data in your database and you should not delete your database file!
Pre-requisite: You must have installed SQL Server Management Studio (Full or Express)
Open SQL Server Management Studio
In the "Connect to Server" window (File->Connect object explorer) enter the following:
Server type : Database Engine
Server name : (localdb)\v11.0
Authentication : [Whatever you used when you created your local db. Probably Windows Authentication).
Click "Connect"
Expand the "Databases" folder in the Object Explorer (View->Object Explorer, F8)
Find your database. It should be named as the full path to your database (.mdf) file
You should see it says "(Pending Recovery)" at the end of the database name or when you try to expand the database it won't be able to and may or may not give you an error message.
This the issue! Your database has crashed essentially..
Right click on the database then select "Tasks -> Detach...".
In the detach window, select your database in the list and check the column that says "Drop Connections"
Click OK.
You should see the database disappear from the list of databases. Your problem should now be fixed. Go and run your application that uses your localdb.
After running your application, your database will re-appear in the list of databases - this is correct. It should not say "Pending recovery" any more since it should be working properly.
The source of the solution: https://www.codeproject.com/Tips/775607/How-to-fix-LocalDB-Requested-Login-failed
I tried to update the user, and it worked. See the command below.
USE ComparisonData// databaseName
EXEC sp_change_users_login #Action='update_one', #UserNamePattern='ftool',#LoginName='ftool';
Just replace user('ftool') accordingly.
I had this problem when I created a WPF .NET Core + Entity Framework Core project and then cloning it on a a new laptop.
Using:
update-database
in the package manager console simply solved it.
To open package manager console go to:
Tools-> Nuget Package Manager -> Package Manager console
I used Windows authentication to connect to local database .mdf file and
my local server was sql server 2014.
My problem solved using this connection string:
string sqlString = " Data Source = (LocalDB)\\MSSQLLocalDB;" + "AttachDbFilename = F:\\.........\\myDatabase.mdf; Integrated Security = True; Connect Timeout = 30";
In my case it is a different issue. The database turned into single user mode and a second connection to the database was showing this exception.
To resolve this issue follow below steps.
Make sure the object explorer is pointed to a system database like master.
Execute a exec sp_who2 and find all the connections to database ‘my_db’. Kill all the connections by doing KILL { session id } where session id is the SPID listed by sp_who2.
USE MASTER;
EXEC sp_who2
Alter the database
USE MASTER;
ALTER DATABASE [my_db] SET MULTI_USER
GO
I ran into this issue when attempting to write to the default database provided in the asp.net mvc template. This was due to the fact that the database hadn't been created yet.
To create the database and make sure that it is accessible follow these steps:
Open up the Package manager console in Visual Studio
Run the command "update-database"
This will create the database an run all the necessary migrations on it.
I have not seen this mentioned in the previous issues, so let me throw out another possibility. It could be that IFItest is not reachable or simply does not exist. For example, if one has a number of configurations, each with its own database, it could be that the database name was not changed to the correct one for the current configuration.
NB: If using a windows service to host the webservice.
You have to insure that your webservice is using the right Log on account to connect to SQL Server.
Open services(I assume the windows service has been install)
Right click on the service and goto properties.
Click on "Log On" Tab
Click on "This account" radio button
Click "Browse"
Enter Pc user name in Text Field and click "Check Name" Button to the right.
Click on text in Text Field, press "OK" button
enter login password and Apply
Inspired by cyptus's answer I used
_dbContext.Database.CreateIfNotExists();
on EF6 before the first database contact (before DB seeding).
If you haven't created the database in your server you will get the same login error.Make sure that the database exist before you login.
it's not a login issue most times. The database might not have been created. To create the database, Go to db context file and add this.Database.EnsureCreated();
The best option would be to use Windows integrated authentication as it is more secure than sql authentication. Create a new windows user in sql server with necessary permissions and change IIS user in the application pool security settings.
I found that I also had to set the UserMapping option when creating a new login and this solved the problem for me. Hope that helps anyone that also found themselves stuck here!
Edit: Setting the login as db owner solved the next problem, too
Some times this trouble may appear if you open this db in another sql server (as example, you launch sql managment studio(SMS) and add this db), and forget stop this server. As result - you app try to connect with user already connected in this db under another server. To fix that, try stop this server by Config. dispatcher sql server.
My apologies about bad english.
Kind regards, Ignat.
In my case the asp.net application can usually connect to database without any problems. I noticed such message in logs. I turn on the SQL server logs and I find out this message:
2016-10-28 10:27:10.86 Logon Login failed for user '****'. Reason: Failed to open the explicitly specified database '****'. [CLIENT: <local machine>]
2016-10-28 10:27:13.22 Server SQL Server is terminating because of a system shutdown. This is an informational message only. No user action is required.
So it seems that server was restarting and that SQL server whad been shutting down a bit earlier then ASP.NET application and the database was not available for few seconds before server restart.
Even if you've set the login as DB owner and set the user mapping for the database that will use the login, check that the actual DB user (not just the login) has the role of 'owner'.
In my case, I was running a Windows Service under "System" identity. The error was:
System.Data.SqlClient.SqlException (0x80131904):
Cannot open database "MyDbName" requested by the login. The login failed.
Login failed for user 'MYDOMAINNAME\HOSTNAME$'.
The problem is that the error is very misleading. Even after I added 'MYDOMAINNAME\HOSTNAME$' login to the database, and granted this login sysadmin access and added a user for that login on my target database, and made that user dbowner, I was still getting the same error.
Apparently I needed to do the same for 'NT AUTHORITY\SYSTEM' login. After I did that, I was able to login without a problem. I don't know why the error message complains about 'MYDOMAINNAME\HOSTNAME$'. I deleted that login and the corresponding user and everything still works.
When using EF Code First, make sure the database exists. You could run the update-database command first.
If none of the above solution is working.
I encountered with the same error message but my issue was completely different. I had just restore my database and the database was in restoring mode. So if your database is in rstoring mode just apply following query.
RESTORE DATABASE MyDatabase
FROM DISK = 'pathToYourDbBackup\MyDatabase.bak'
WITH REPLACE,RECOVERY
I had this happen to me when I deleted the DB and forgot to recreate it. It happens sometimes, since Database folder needs refresh.
If you didn't have any problems before and you get this error only in the package manager console, you don't need to do anything special. Just open the sql server object explorer window and connect and run the command again in the console.

Categories