Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify a username using connection string in Entity Framework

My ASP.Net Core app keeps trying to login into database using a "default" username even though I specify a different user in a connection string, which I am using. That is I keep getting the same exception that says:

An unhandled exception occurred while processing the request. SqlException: Cannot open database "testDB" requested by the login. The login failed. Login failed for user 'DESKTOP-555DDD\skorejen'.

Even though I am using a connection string that has a different username defined.

How can I fix it so that my app logins with the connection-string specified username?

Connection String:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=testDB;User Id=myusername;Trusted_Connection=True;"
  },

ASP.Net Core Startup.cs file:

public void ConfigureServices(IServiceCollection services)
        {
             services.AddDbContext<OrderContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        }
like image 960
Skorejen Avatar asked Jul 13 '26 05:07

Skorejen


2 Answers

Your ConnectionStrings has to be in below formats:

With credentials (SQL authentication):

"ConnectionStrings": {
  "DefaultConnection": "Server=myServerAddress; Database=myDataBase; User Id=myUsername; Password=myPassword; Trusted_Connection=false; MultipleActiveResultSets=true;"
}

Without credentials (Windows authentication):

"ConnectionStrings": {       
  "DefaultConnection": "Server=myServerAddress; Database=myDataBase; Trusted_Connection=True; MultipleActiveResultSets=true"        
} 
like image 181
Reyan Chougle Avatar answered Jul 15 '26 18:07

Reyan Chougle


You will need to enable sql authentication mode, add the user to the sql server logins and specify the password in the connection string.

Example connection string:

Server=myServerAddress;Database=myDataBase;User Id=myUsername; Password=myPassword;

(source)

Eanabling sql authentication mode:

enter image description here

like image 43
Stefan Avatar answered Jul 15 '26 18:07

Stefan