Search code examples
c#.net-coreentity-framework-core.net-6.0ef-core-6.0

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


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?


Solution

  • 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"));