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