Rob L
Rob L

Reputation: 2372

Cannot connect to a database in .NET Core 3.x (connection string in appsettings.json)

In my "Models" project (not the main ASP.NET project with the Controllers/Views and appsettings.json) I have the following code generated using dotnet ef....

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.

                optionsBuilder.UseSqlServer("Server=.;Database=MyDB;Trusted_Connection=True;");
            }
        }

It works, I can connect to the database.

However, that warning indicates the connection string should be in the appsettings.json file in the main asp.net project. I've moved it there, but now I just cannot work out what I have to pass to the UseSqlServer() method to use the connection string in the appsettings.json file and access the database in the preferred way.

  "ConnectionStrings": {
    "MyLocalDatabase": "Server=.;Database=MyDB;Trusted_Connection=True;"
  },

There are a few ideas on the web, but none seem to relate to the latest .net core 3.x.

Any help appreciated. Thanks.

Upvotes: 0

Views: 268

Answers (2)

Rob L
Rob L

Reputation: 2372

My issue was that it no longer seemed to like me doing

using (var context = new MyDb())
{
    dadeda...
}

I now inject the context into the controller/service (for example) and then use that each time.

_context.dadeda

Just a different way from the way I was doing it in my none-core app.

Upvotes: 0

Saleh Bagheri
Saleh Bagheri

Reputation: 434

You can pass connection string name to UseSqlServer in the Startup.cs file like below:

options.UseSqlServer(Configuration.GetConnectionString("MyLocalDatabase")));

You should also inject the Configuration in the Startup.cs file or where you want to use it.

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

public IConfiguration Configuration { get; }

Upvotes: 1

Related Questions