Read Configuration from appsettings.json in Entity Framework

After you have done the scaffolding task, the configuration details gets hard-coded on the source code. We have to read connection string from the config file.

Open the DbContext class and comment the warning message in the OnConfiguring method.

Currently, the connection string is hardcoded. It is always a good practice not to keep the configuration details inside the code. We will use the appsettings.json file to keep these details. Create a file with the above name in the project directory.

Add the below content in appsettings.json file.

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DBConnectionString": "data source=(localdb)\\MSSQLLocalDB;initial catalog=EmployeeDB;Integrated Security=true"
  }
}

Modify the OnConfiguring method in DbContext class to read the connection string from above file.

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            var builder = new ConfigurationBuilder()
                              .SetBasePath(Directory.GetCurrentDirectory())
                              .AddJsonFile("appsettings.json");
            var config = builder.Build();
            var connectionString = config.GetConnectionString("DBConnectionString");
 
            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(connectionString);
            }
        }

Import the following :

using Microsoft.Extensions.Configuration;
using System.IO;

Thank you All!!! Hope you find this useful.


Up ↑

%d bloggers like this: