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

10

6

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?

Braunstein answered 2/2, 2022 at 15:30 Comment(0)
B
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"));
Braunstein answered 5/2, 2022 at 9:58 Comment(3)
Having same above issue , used above code but still its not workingDotted
This is a misleading answer. This is completely redundant to the default convention of WebApplication.CreateBuilder()Moulin
I second @AdamVincent in this. It seems like OP is actually having an issue with context pathMonika
O
4

For the people reaching this question based on the google search of the error:

I got this error while running Scaffold-DbContext command, creating entities in DB first approach.

For me it was unrelated to the connection string altogether. It was due to an application runtime error where the DI was not able to resolve one of the repositories. I added the service in the IServiceCollection and it worked fine!

Outstay answered 31/3, 2023 at 2:27 Comment(0)
M
3

Arrgh! I had a similar problem, and tried all the answers here, but no luck.

Finally, it turned out that I had an OnConfiguring method in my DbContext:

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

When I removed those lines, everything worked! Hope this helps someone.

Mendenhall answered 20/12, 2023 at 1:11 Comment(0)
L
2

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.

Loreleilorelie answered 2/2, 2022 at 15:53 Comment(1)
the base path, json file (including environment overrides), environment variables, and even command-line parameters are all done by default in .NET core 6 with the single line WebApplication.CreateBuilder(args);Abruption
A
1

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.

Attributive answered 5/8, 2022 at 14:46 Comment(0)
P
1

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 ASP.NET 6 API

Praxiteles answered 23/9, 2022 at 17:34 Comment(0)
S
1

I was having a similar issue using .NET8. Here is what fixed it for me -- basically I followed the instructions given by a more detailed exception message I managed to coax out of the system while trying stuff out!

First in Program.cs:

builder.Services.AddDbContext<PgcContext>(options => options.UseSqlServer("name=DefaultConnection"));

Then in my DbContext:

public PgcContext(DbContextOptions<PgcContext> options) : base(options) {}

I also deleted the override I had for OnConfiguring() in the DbContext. That was it, everything worked great. This works whether you are using an explicit connection string or a named connection string.

Snowdrop answered 5/9 at 20:42 Comment(0)
K
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
    }
}
Kicksorter answered 2/2, 2022 at 20:26 Comment(1)
I already tried without name=; no different. Also as I mentioned in Q builder.Configuration.GetConnectionString returns null.Braunstein
H
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"));
Hasp answered 2/2, 2022 at 20:37 Comment(0)
B
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"));
Braunstein answered 5/2, 2022 at 9:58 Comment(3)
Having same above issue , used above code but still its not workingDotted
This is a misleading answer. This is completely redundant to the default convention of WebApplication.CreateBuilder()Moulin
I second @AdamVincent in this. It seems like OP is actually having an issue with context pathMonika
C
-5

Hello, the highlighted code worked for

[1]: https://static.mcmap.net/file/mcmap/ZG-AbGLDKwfpKnMxcF_AZVLQamyA/Sv8s2.png

Cucurbit answered 26/9, 2022 at 15:18 Comment(2)
Please take the tour, read How to Answer, read meta.https://mcmap.net/q/12237/-windows-cmd-pipe-not-unicode-even-with-u-switch ; and consider using stackoverflow.com/editing-helpAnonymous
While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From ReviewSquander

© 2022 - 2024 — McMap. All rights reserved.