1 year ago
#77543

Mike Ooi
EF Core on .net5 - AddDbContext not working
This has been driving me up the wall as there should be no reason why AddDbContext in startup.cs isn't working. Anyone have any thoughts?
Project specs: .net 5, EF Core 5, MVC
PsContext.cs
public PsContext()
{
}
public PsContext(DbContextOptions<PsContext> options)
: base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer("name=PSDB");
}
}
Startup.cs
services.AddDbContext<PsContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("PSDB"));
});
Appsettings.json
"ConnectionStrings": {
"PSDB": "Server=xxxxxx;Database=xxxxxxx;User ID=xxxxxxx;Password=xxxxxx;MultipleActiveResultSets=true"
},
I scaffolded my DB Entity without issue by using the following command in Package Manager Console
Scaffold-DbContext -Connection name=PSDB Microsoft.EntityFrameworkCore.SqlServer -OutputDir Entities -f
However when running the application, I encounter this error
System.InvalidOperationException: 'A named connection string was used, but the name 'PSDB' 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.'
As requested, here is the program.cs as well
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.Sources.Clear();
var env = hostingContext.HostingEnvironment;
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
c#
asp.net-core
.net-core
entity-framework-core
.net-5
0 Answers
Your Answer