skip to Main Content

I’m trying to use appsettings.json to store the database connection string to use different strings for build configurations. But, I’m getting this exception:

System.InvalidOperationException: A named connection string was used, but the name ‘ConnectionStrings:DefaultConnection’ was not found in the application’s configuration.

Here is my appsettings.json:

"ConnectionStrings": {
    "DefaultConnection": "Server=adserver\VALLOUREC;Database=eddb000;user id=devnepre;Password=nepre;MultipleActiveResultSets=False;TrustServerCertificate=True"
}

And here is how is my database context configuration:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    => optionsBuilder.UseSqlServer("Name=ConnectionStrings:DefaultConnection");

In program.cs, the settings are loaded like this:

builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

And I use AddDbContext but that doesn’t change anything.

I tried some solutions suggested in this topic, but these did not work.

I know I can put the connection string directly in the OnConfiguring function, but I don’t want to do this because every time I scaffold the database, the code is changed and I need to revert this part.

Edit: when i Scaffold the database with this command:

Scaffold-DbContext Name=ConnectionStrings:DefaultConnection Microsoft.EntityFrameworkCore.SqlServer - force

the OnConfiguring is aways replaced by this:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    => optionsBuilder.UseSqlServer("Name=ConnectionStrings:DefaultConnection");

i’m trying to make it works with this implementation to avoid needs to change every time o run the command.

3

Answers


  1. Chosen as BEST ANSWER

    Sorry, i took a while to realize that the error was not comming from my main DbContext. The project has a second Database Context that inherit the first one.

    I juest need to add this code:

    builder.Services.AddDbContext<ExampleDbContext>(options =>
    options.UseSqlServer(
        builder.Configuration.GetConnectionString("DefaultConnection")));
    

    for this second and it's work. The inherited DbContext was not able to instance it's parent until i implement the roght constructor receiving the DbContextOptions<>


  2. as far as I know asp.net uses .net generic host, when I did some research I found that we can get configuration values or settings through the IConfiguration interface, to do so, create a new constructor that asks for the IConfiguration type through parameters, assign the IConfiguration parameter to a field and then use it as in the following code to get the data from your config file in this example its appsettings.json,

    public class ExampleDbContext : DbContext
    {
        private readonly IConfiguration _configuration;
        public ExampleDbContext(IConfiguration configuration)
        {
            _configuration = configuration;
            Console.WriteLine(_configuration["ConnectionStrings:DefaultConnection"]);
        }
        
    
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder.UseSqlServer(_configuration["ConnectionStrings:DefaultConnection"]);
    }
    

    To enable depency injection for our ExampleDbContext we can use the following code in our builder

    var builder = WebApplication.CreateBuilder(args);
    //other services, middleware, etc.
    builder.Services.AddDbContext<ExampleDbContext>();
    var app = builder.Build();
    

    note: i tried the following code in asp.net minimal api’s and it worked. i am not sure about asp.net mvc version

    Login or Signup to reply.
  3. You should be able to use IConfiguration interface with registered settings from defined sources (appsettings.json in your case).

    So, during registration process, you just call:

    builder.Services.AddDbContext<ExampleDbContext>(options =>
        options.UseSqlServer(
            builder.Configuration.GetConnectionString("DefaultConnection")));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search