A named connection string was used, but the name 'DefaultConnection' was not found in the application's configuration

Viewed 3138

I have a DbContext named FileManagerContext in my DOTNET 6 API:

public class FileManagerContext : DbContext {
    public FileManagerContext(DbContextOptions<FileManagerContext> options) : base(options) { }
    protected override void OnModelCreating(ModelBuilder modelBuilder) {
        base.OnModelCreating(modelBuilder);
        modelBuilder.ApplyConfigurationsFromAssembly(GetType().Assembly);
    }
}

It's a pretty simple DbContext with a simple Entity in it. Anyway, I have this appsettings.json too:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "ConnectionStrings": {
    "DefaultConnection": "Server=localhost;Database=FM;User=SA;Password=1234;"
  },
  "AllowedHosts": "*"
}

And here is the startup snippet in Program.cs's top level statement:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<FileManagerContext>(
    opt => opt.UseSqlServer("name=DefaultConnection"));

I could use migrations in the case. All thing goes good. I can add migrations and I can update database successfully. But when I run the application and try to use DbContext I get this error:

System.InvalidOperationException: A named connection string was used, but the name 'DefaultConnection' was not found in the application's configuration. Note that named connection strings are only supported when using 'IConfiguration' and a service provider, such as in a typical ASP.NET Core application. See https://go.microsoft.com/fwlink/?linkid=850912 for more information.

I've also tried to get the connection string like this:

var cs = builder.Configuration.GetConnectionString("DefaultConnection");

But it returns null. Can anybody help me through please?

6 Answers

From the sounds of the error, your configuration might not be getting picked up.

How is the configuration being created?

Do you see AddConfiguration extension method being called on the Webhost? the contents of the method should look something like the following:

IConfiguration config = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json", false, false)                                           
                          .AddJsonFile($"appsettings.{envLower}.json", true, true)
                          .AddEnvironmentVariables()
                          .Build();

The the call to build may or may not exist. We typically manually create the configuration object because we need to construct the Loggers and then use AddConfiguration extension method to add that object to the host.

If you don't see that, please take a look at the documentation from Microsoft for guidance on how to set it up. Configuration Documentation

Alternatively, you can get the connection string via the Configuration Object and pass it to the UseSqlServer method.

services.AddDbContext<FileManagerContext>((provider, options) => {
           IConfiguration config = provider.GetRequiredService<IConfiguration>();
           string connectionString = config.GetConnectionString("DefaultConnection");
           options.UseSqlServer(connectionString);                             
         });

in the alternate method, a service provider is passed to the action. You can use the provider to fetch the IConfiguration object from the DI container.

Don't use "name=DefaultConnection" since it is treated as connection string name including "name="

I am using this syntax in program.cs and everything is working properly

var builder = WebApplication.CreateBuilder(args);

.......

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

and since you are using Ms Sql Server , the connection string for sql server is usually like this

"DefaultConnection": "Data Source=xxxx;Initial catalog=xxx;Integrated Security=False;User ID=xxxx;Password=xxxx;"

and my OnConfiguring code looks like this

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
   if (!optionsBuilder.IsConfigured)
   {
       ...your code
    }
}

use builder.Configuration

builder.Services.AddDbContext<FileManagerContext>(options => 
{
    options.UseSqlServer(builder.Configuration["ConnectionStrings:DefaultConnection"]);
});

or builder.Configuration.GetConnectionString as @Serge mentions

options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));

Thanks To @Neil I figured it out. The configurations were not loaded into app. But, since I'm in dotnet 6's top level statements, adding configurations seems a little bit different from @Neil's advice. So here is the working solution:

builder.Services.AddControllers();

var currentDirectory = AppDomain.CurrentDomain.BaseDirectory;
var environmentName = builder.Environment.EnvironmentName;

builder.Configuration
    .SetBasePath(currentDirectory)
    .AddJsonFile("appsettings.json", false, true)
    .AddJsonFile($"appsettings.{environmentName}.json", true, true)
    .AddEnvironmentVariables();

// blah blah 
builder.Services.AddDbContext<FileManagerContext>(
    opt => opt.UseSqlServer("name=DefaultConnection"));

I was trying to scaffold the DB changes by this command :

Scaffold-DbContext -Connection name=YourDBContextObjectName -Provider 
  Microsoft.EntityFrameworkCore.SqlServer -project Destination_NameSpace 
    -context YourDBContextObjectName -OutputDir Entities -force

But the issue is the same in the code-first approach as well, In my scenario, I had different appsettings for different ENVs.

enter image description here

The appSettings.json was like so (as you can see, there is connectionStrings information in this file:

enter image description here

Also, my appsettings.dev.json was like so : enter image description here

The problem is being occurred because when I tried to scaffold the DB changes by command, Firstly it tries to build your project, and because the Redis and RabbitMQ connection information is missed in the appsettings.json file, It cannot connect to the dataSources. so It returns the error.

An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: Object reference not set to an instance of an object. System.InvalidOperationException: A named connection string was used, but the name 'DBContextName' was not found in the application's configuration. Note that named connection strings are only supported when using 'IConfiguration' and a service provider...

Solution :

  1. Set The correct Project as the Startup project
  2. Add missing information about other connections to the appsettings.json

As you see, regardless of the error, It's not always related to the Database connection string.

I had the same problem but the error occurs when the application was published on the server. My string connection is in the user's secret, what I did was the following:

In program.cs

// Add services to the container.

builder.Services.AddDbContext<DataContext>(options =>
{
    options.UseSqlServer("Name=dbconnection");
});
builder.Services.AddDbContext<DataContext>();

And before publish, select the string connection in data base options and make sure it is the correct:

Publish Options

It works for me in dot 6 API

Related