EF Core双DbContext配置异常:SKGDMD_WebSiteContext未配置数据库提供程序
解决EF Core多DbContext注入时未配置数据库提供程序的问题
核心问题分析
你遇到的AggregateException提示未配置数据库提供程序,大概率是以下几个原因:
- 代码中直接使用无参构造函数实例化
SKGDMD_WebSiteContext,跳过了依赖注入的配置 OnConfiguring方法存在但未做判断,导致DI注入的配置被忽略- 连接字符串读取失败,DI注册时未正确绑定SqlServer提供程序
分步解决方案
1. 修复SKGDMD_WebSiteContext的OnConfiguring方法
保留该方法但添加判断,确保只有在DI未配置时才触发逻辑,避免覆盖注入的配置:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { // 生产环境不要硬编码,这里仅作调试提示 throw new InvalidOperationException("请通过依赖注入配置DbContext的数据库提供程序"); } }
2. 确保所有实例化都通过依赖注入完成
检查代码中是否有new SKGDMD_WebSiteContext()的写法,必须改为构造函数注入:
// 示例:控制器中注入 public class YourController : Controller { private readonly SKGDMD_WebSiteContext _dbContext; public YourController(SKGDMD_WebSiteContext dbContext) { _dbContext = dbContext; } // 业务逻辑中直接使用_dbContext即可 }
3. 验证连接字符串与DI注册的正确性
- 确认
appsettings.json中存在正确命名的连接字符串:{ "ConnectionStrings": { "DefaultConnection": "Server=你的服务器地址;Database=你的数据库名;Trusted_Connection=True;TrustServerCertificate=True;" } } - 可以在
Program.cs中添加调试输出,确认连接字符串读取正常:var connectionString = builder.Configuration.GetConnectionString("DefaultConnection"); // 调试时查看控制台输出,确认连接字符串不为空 Console.WriteLine("读取到的连接字符串:" + connectionString); builder.Services.AddDbContext<SKGDMD_WebSiteContext>(options => options.UseSqlServer(connectionString));
4. 简化DI注册(可选)
可以合并AddDatabaseDeveloperPageExceptionFilter的调用,避免重复:
var builder = WebApplication.CreateBuilder(args); var connectionString = builder.Configuration.GetConnectionString("DefaultConnection"); // 注册两个DbContext builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionString)); builder.Services.AddDbContext<SKGDMD_WebSiteContext>(options => options.UseSqlServer(connectionString)); // 只添加一次开发者异常筛选器 builder.Services.AddDatabaseDeveloperPageExceptionFilter(); // Identity配置不变 builder.Services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true) .AddRoles<IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>(); builder.Services.AddRazorPages();
验证方法
启动程序后,在使用SKGDMD_WebSiteContext的地方打个断点,检查_dbContext.Database.ProviderName是否为Microsoft.EntityFrameworkCore.SqlServer,如果是则说明配置生效。
内容的提问来源于stack exchange,提问作者cbas007
相关产品推荐
相关产品推荐

