插入MySQL记录时提示DbContext未配置数据库提供者该如何解决?
问题原因
- 你在控制器中手动通过
new HelloDataContext()实例化数据库上下文时,该上下文没有任何数据库提供程序、连接字符串的相关配置,既没有重写OnConfiguring方法做内置配置,也没有通过依赖注入获取已经配置好的上下文实例。 HelloDataContext仅定义了无参构造函数,就算你在启动类中已经用AddDbContext注册了上下文,手动实例化时也无法读取到注册的配置信息。- 额外说明:直接把ViewModel作为EF Core实体放到
DbSet中不属于最佳实践,建议单独定义实体模型再做映射,不过这不是本次报错的直接诱因。
解决步骤
1. 修改HelloDataContext构造函数,支持接收配置参数
public class HelloDataContext : IdentityDbContext<IdentityUserHelper> { // 新增带DbContextOptions参数的构造函数,将参数传递给基类 public HelloDataContext(DbContextOptions<HelloDataContext> options) : base(options) { } public DbSet<Quotation> quotation { get; set; } public DbSet<HelpDeskViewModel> table1 { get; set; } }
2. 在程序启动配置中注册DbContext
如果是.NET 6+ 版本在Program.cs中添加如下配置,旧版本在Startup.cs的ConfigureServices方法中添加:
// 注意要提前安装对应数据库的EF Core Provider包,比如用SqlServer就安装Microsoft.EntityFrameworkCore.SqlServer builder.Services.AddDbContext<HelloDataContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
同时在appsettings.json中添加对应的数据库连接字符串:
{ "ConnectionStrings": { "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=你的数据库名;Trusted_Connection=True;MultipleActiveResultSets=true" } }
3. 控制器通过构造函数注入获取HelloDataContext实例,不要手动new
public class 你的控制器名称 : Controller { private readonly HelloDataContext _db; // 构造函数注入已经配置好的上下文 public 你的控制器名称(HelloDataContext db) { _db = db; } [HttpPost] public IActionResult GetTicket(HelpDeskViewModel h) { if (ModelState.IsValid) { _db.table1.Add(new HelpDeskViewModel { ticketID = h.ticketID, category = h.category, description = h.description }); _db.SaveChanges(); } return RedirectToAction("Feedback"); } }
可选方案:如果需要支持手动实例化上下文,可重写OnConfiguring方法
如果不想用依赖注入的方式,直接在HelloDataContext类中添加如下代码即可:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { // 直接配置数据库提供程序和连接字符串 optionsBuilder.UseSqlServer("你的完整数据库连接字符串"); } }
注意事项
- 安装的数据库Provider Nuget包版本必须和你项目使用的EF Core版本一致,版本不匹配也可能引发配置异常。
内容的提问来源于stack exchange,提问作者squigee90
相关产品推荐
相关产品推荐

