Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

876
Visualizações
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?

over 4 years ago · Santiago Trujillo
4 Respostas
Responde à pergunta

0

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.

over 4 years ago · Santiago Trujillo Relatório

0

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
    }
}
over 4 years ago · Santiago Trujillo Relatório

0

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"));
over 4 years ago · Santiago Trujillo Relatório

0

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"));
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda