0

I am trying to generate a connection to the database in ASP.NET Core MVC, but when trying to enter the index page of my miles controller, it generates an error, because the connection to the database has not been made.

This is my appsettings.json:

"ConnectionStrings": {
    "MillaContext": "Server=server;Database=Bit_V2;User Id=sa; Password=password;Trusted_Connection=True;MultipleActiveResultSets=true"
}

This is my startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    ...

    services.AddDbContext<MillaContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("MillaContext")));
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

And this is error:

enter image description here

Serge
  • 40,935
  • 4
  • 18
  • 45
cosmos multi
  • 543
  • 1
  • 6
  • 13
  • This is an common error and means there is no connection between your service and the database server. [see more](https://stackoverflow.com/questions/1391503/) – Hamed Naeemaei Feb 10 '21 at 20:02
  • 2
    Also: you should **never** have both `Trusted_Connection=true` and an explicit User Id and password in your connection string. Do you know which one prevails?? The "trusted connection" with the currently logged in user credentials, or the explicitly defined values?? Pick the one that works in your case - but **do NOT** use both at the same time. – marc_s Feb 10 '21 at 21:41
  • The solution to the question, which credentials will be used, is in the [docs](https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/connection-string-syntax): *Windows authentication takes precedence over SQL Server logins. If you specify both Integrated Security=true as well as a user name and password, the user name and password will be ignored and Windows authentication will be used.* – marc_s Feb 10 '21 at 21:43
  • `error: 26 - Error Locating Server/Instance Specified` usually indicates that you have `Server=ServerNameOrIpAddress\InstanceName` in your connection string and that the SQL Browser Service on the target computer either isn't running or isn't accessible via udp/1434 due to firewall rules. If you know the TCP port used by the named instance (e.g.: 1433) you can avoid this issue by using `Server=tcp:ServerNameOrIpAddress,1433` instead. – AlwaysLearning Feb 11 '21 at 02:55
  • I tried it that way but my keeps generating the same error – cosmos multi Feb 11 '21 at 12:34

1 Answers1

1

Since you are using sql server, your connection string should be like this:

"MillaContext": "Data Source=server;Initial Catalog=Bit_V2;Integrated Security=False;
User ID=sa;Password=password;"
Serge
  • 40,935
  • 4
  • 18
  • 45