Reading Entity Framework Core connection string from appSettings.json

When you run Scoffold-DbCotext with a connection string EF Core will scaffold your DB but will put the hardcoded connection string in the OnConfiguring method of your new DbContext class. If you prefer having Entity Framework Core read the connection from an appSettings file this is easily done. Note the below code works as of EF Core 3.1.7.

If your appSettings has a connection string for ‘BloggingDatabase’…

appSettings config example

You can run Scaffold-DbContext with the Name parameter which points to your connection String name.

Scaffold with named connection

This will cause EF to rebuild your objects and generate an onConfiguring method similar to below..

onconfiguring method

However we can ignore this as we’re going to configure our connection string and any other DbContext related options in the Startup.cs file. Below we setup appSettings.json to be used as our configuration and in the ConfigureServices method we add a DbContext and set its connection string.

Startup.cs registering DBContext

To actually query against the DbContext we’ve added we can inject an instance of it into our controllers constructor. This makes it very clear to other developers that the controller relies on the EFContext class and since Dependency Injection is built into .NET Core is very easy to do.

DbContext Inject

Alternatively rather than injecting specific services we can inject an instance of IServiceProvider and use its GetService method to get an instance of our EFContext class.

Inject IServiceProvider

You might prefer the IServiceProvider approach if your controller has a lot of dependencies. In most cases however I’d recommend injecting specific dependencies as its a little more obvious to other developers what services a controller depends on.

One thought on “Reading Entity Framework Core connection string from appSettings.json”

Leave a Reply

Your email address will not be published. Required fields are marked *