Home > Net >  I'm unable to connect to my local SQL Server
I'm unable to connect to my local SQL Server

Time:07-05

I am trying to connect to my SQL Server local database:

builder.Services.AddDbContextPool<UserDbContext>(options =>
{
        options.UseSqlServer(builder.Configuration.GetConnectionString("ConnectionString"), o =>
        {
               o.EnableRetryOnFailure();
        });
});

API controller:

[ApiController]
[Route("[controller]")]
public class UserController : Controller
{
    private readonly UserDbContext userDbContext;

    public UserController(UserDbContext dbContext) => userDbContext = dbContext;

    [HttpGet]
    [Route("all")]
    public ActionResult<IEnumerable<User>> GetAllUsers()
    {
        IEnumerable<User> allUsers = userDbContext.Users;
        return Ok(allUsers);
    }
}

And here is my connection string:

"ConnectionString": "server=(localdb)\\MSSQLLocalDB;Database=todoapp;User ID=todouser;Password=1234"

Now, when I am trying to send GET request, I get response:

Microsoft.Data.SqlClient.SqlException (0x80131904): Login failed for user 'todouser'.

With SQL Server Management Studio, I can connect to the database without any problems. Server authentication is set to: "SQL Server and Windows authentication mode", but I cannot connect with Windows authentication as well.

CodePudding user response:

Try changing the connection-string to use Windows Authentication:

"ConnectionString": "server=(localdb)\\MSSQLLocalDB;Database=todoapp;Trusted_Connection=True"

CodePudding user response:

if you want to connect with todouser you must first create it:

  1. go to computer management via win x next in left panel go to LocalUser and Groups and next in right panel add new user with username todouser and password 1234
  2. next you must go to MSSQL MS and go to security>login>right click on todouser>properties on right set default db to todoapp -- in User Mapping check the todoapp database.
  • Related