调试时出现DbContext未配置数据库提供程序错误求助
调试时触发错误:No database provider has been configured for this DbContext in debug
调试程序时突然弹出错误:No database provider has been configured for this DbContext in debug,试过网上的各种解决方案都无效,求帮忙。
相关代码如下:
StartUp.cs
public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer( Configuration.GetConnectionString("DefaultConnection"))); services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = false) .AddEntityFrameworkStores<ApplicationDbContext>(); services.AddControllersWithViews(); services.AddRazorPages(); services.AddScoped<IDAL, DAL>(); }
DAL & IDAL.cs(错误触发位置)
namespace CalendarioTrabalho.Data { public interface IDAL { public List<Evento> GetEventos(); public List<Evento> GetMeusEventos(string userid); public Evento GetEvento( int id); } public class DAL : IDAL { private ApplicationDbContext db = new ApplicationDbContext(); public List<Evento> GetEventos() { return db.Eventos.ToList(); } public List<Evento> GetMeusEventos(string userid) { return db.Eventos.Where(x => x.User.Id == userid).ToList(); } public Evento GetEvento(int id) { return db.Eventos.FirstOrDefault(x => x.Id == id); } } }
问题根源
错误出在DAL类里直接通过new ApplicationDbContext()实例化上下文。你在StartUp中已经通过依赖注入配置了DbContext的数据库提供器,但手动new出来的上下文实例不会使用这些配置,EF Core无法识别要使用的数据库驱动,因此抛出错误。
解决方案
修改DAL类,通过构造函数注入ApplicationDbContext,而不是手动实例化:
修改后的DAL代码
namespace CalendarioTrabalho.Data { public interface IDAL { List<Evento> GetEventos(); List<Evento> GetMeusEventos(string userid); Evento GetEvento(int id); } public class DAL : IDAL { private readonly ApplicationDbContext _db; // 构造函数注入DbContext public DAL(ApplicationDbContext db) { _db = db; } public List<Evento> GetEventos() { return _db.Eventos.ToList(); } public List<Evento> GetMeusEventos(string userid) { return _db.Eventos.Where(x => x.User.Id == userid).ToList(); } public Evento GetEvento(int id) { return _db.Eventos.FirstOrDefault(x => x.Id == id); } } }
确保ApplicationDbContext有正确的构造函数
你的ApplicationDbContext需要定义接收DbContextOptions<ApplicationDbContext>参数的构造函数,这样依赖注入容器才能把配置好的选项传递进去:
public class ApplicationDbContext : DbContext { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } // 定义你的DbSet public DbSet<Evento> Eventos { get; set; } public DbSet<ApplicationUser> Users { get; set; } }
原理说明
依赖注入容器会管理ApplicationDbContext的生命周期,并且自动把你在StartUp中配置的SqlServer连接选项注入到上下文实例中。通过构造函数注入获取的上下文,会自动应用这些配置,EF Core就能识别并使用对应的数据库提供器了。
内容的提问来源于stack exchange,提问作者Mario Salamanca
相关产品推荐
相关产品推荐

