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’…
You can run Scaffold-DbContext with the Name parameter which points to your connection String name.
This will cause EF to rebuild your objects and generate an onConfiguring method similar to below..
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.
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.
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.
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”
How would one access your “HomeController” from a razor component?