I am using .NET 6 and Entity Framework Core 6 in a new ASP.NET Core MVC web app. I have my connection string set in user-secrets. I was able to perform a
dotnet ef dbcontext scaffold Name=ConnectionStrings:someconn
without any trouble. My model context was created. Now I want to do a simple query, but the builder in program.cs
is complaining about not finding the connection.
Here I create a builder
var builder = WebApplication.CreateBuilder(args);
var currentDirectory = AppDomain.CurrentDomain.BaseDirectory;
var environmentName = builder.Environment.EnvironmentName;
builder.Configuration
.SetBasePath(currentDirectory)
.AddUserSecrets<Program>()
.AddEnvironmentVariables();
var connectionString = builder.Configuration.GetConnectionString("ConnectionStrings:someconn ");
Here I place this code inside program.cs, and just before app.Run.
using (var ctx = new ModelContext())
{
List<SomeModel> pd = ctx.SomeModel
.Where(p => p.Id == "12345").ToList();
}
app.Run();
Error
A named connection string was used, but the name 'ConnectionStrings:someconn' was not found in the application's configuration
Here's a sample for reading a connection string from appsettings.json. (for simplicity I've used a sample for sqlite, which shouldn't affect they general way of reading the string.)
Hope this helps.
appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Information",
"Microsoft.AspNetCore": "Information"
}
},
"ConnectionStrings": {
"someconn": "Data Source=some.sqlite"
}
}
and the in Program.cs
var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("someconn")
A reason could be that the appsettings.json
isn't found. Maybe check if this part of the code is needed or execute it after reading the connection string.
var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("someconn")
var currentDirectory = AppDomain.CurrentDomain.BaseDirectory;
var environmentName = builder.Environment.EnvironmentName;
builder.Configuration
.SetBasePath(currentDirectory)//check if this is necessary
.AddUserSecrets<Program>()
.AddEnvironmentVariables();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.