ASP.NET Core MVC中EF Core与Identity的InvalidOperationException问题
解决"未为此DbContext配置数据库提供程序"异常的方案
问题根源
你手动通过new ApplicationDbContext()实例化上下文时,调用的是无参构造函数,这个构造函数并没有使用Startup中配置的DbContextOptions,导致EF Core无法识别要使用的数据库提供程序。而依赖注入(DI)机制会自动传递配置好的选项,这才是正确的使用方式。
具体解决步骤
1. 移除ApplicationDbContext的无参构造函数
只保留接收DbContextOptions<ApplicationDbContext>的构造函数:
public class ApplicationDbContext : IdentityDbContext { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } public DbSet<Product> Products { get; set; } }
2. 通过构造函数注入获取上下文
修改ProductsController,让DI容器自动注入ApplicationDbContext实例,而非手动new:
public class ProductsController : Controller { private readonly ApplicationDbContext _context; // 构造函数注入上下文 public ProductsController(ApplicationDbContext context) { _context = context; } // GET: Products/Edit/5 public async Task<IActionResult> Edit(int? id) { if (id == null) { return NotFound(); } var existingProduct = await _context.Products.FindAsync(id); if (existingProduct == null) { return NotFound(); } return View(existingProduct); } // POST: Products/Edit/5 [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, [Bind("Id,Name,Price,Description")] Product product) { if (id != product.Id) { return NotFound(); } if (ModelState.IsValid) { try { _context.Update(product); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ProductExists(product.Id)) { return NotFound(); } else { throw; } } return RedirectToAction(nameof(Index)); } return View(product); } private bool ProductExists(int id) { return _context.Products.Any(e => e.Id == id); } }
3. 确认数据库上下文配置正确
确保Startup.cs(.NET 5及更早)或Program.cs(.NET 6+)中的AddDbContext配置无误:
// .NET 5及更早 Startup.cs ConfigureServices方法 services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); // .NET 6+ Program.cs builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
原理说明
依赖注入容器会自动将Startup/Program中配置好的DbContextOptions传递给ApplicationDbContext的有参构造函数,这样上下文就能正确识别要使用的SQL Server提供程序,避免手动实例化时的配置缺失问题。同时,构造函数注入也是ASP.NET Core推荐的服务使用方式,能保证上下文实例的生命周期管理符合框架规范。
内容的提问来源于stack exchange,提问作者ross
相关产品推荐
相关产品推荐

