c# - 没有为此 DbContext 配置数据库提供程序,即使将 DbContextOptions 传递给构造函数
问题描述
我在网上看到了很多问题,但是答案似乎是确保您的 DbContext 类具有 DbContextOptions 的构造函数。
但是,我已经调试过,我可以看到正在调用正确的构造函数,但是我仍然收到“没有为此 DbContext 配置数据库提供程序”错误:(
这是我的 Controller.cs 中的相关代码:
Microsoft.EntityFrameworkCore.DbContextOptions<CoreContext> options = new Microsoft.EntityFrameworkCore.DbContextOptions<CoreContext>();
using (CoreContext dbContext = new CoreContext(options))
{
dbContext.Person.Add(person);
dbContext.SaveChanges();
id = person.PkPersonId;
}
这是我的 CoreContext.cs 的构造函数:
public CoreContext(DbContextOptions<CoreContext> options)
: base(options)
{
}
这是我的 Startup.cs 配置方法:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddIdentity<IdentityUser, IdentityRole>(options => { options.Password.RequiredLength = 10; })
.AddEntityFrameworkStores<CoreContext>();
services.AddDbContext<CoreContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("BloggingDatabase")));
}
解决方案
您需要在 DBContext 下定义实体详细信息,然后才能访问数据库实体,否则您将收到错误消息。因此,请按照以下代码解决此问题。
public CoreContext(DbContextOptions<CoreContext> options): base(options)
{
public virtual DbSet<Person> Persons { get; set; }
}
推荐阅读
- opentext - EXTream 中的慢跑使用
- google-bigquery - BigQuery中2个源表(左外连接查询)匹配时如何返回单行
- react-native - React navigation 5 - 从一个堆栈导航到另一个嵌套堆栈
- flutter - 颤振块:变量未在 BlocBuilder 中定义
- performance - 火花中的广播变量导致性能问题
- javascript - 如何使用新的 Trusted Types 标头和 reCAPTCHA?
- jasper-reports - ireport excel 输出包含空格而不是空列
- python - 如何使列表和字典的功能成为摘要?
- delphi - 为什么 MSFT_PhysicalDisk 总是返回磁盘大小 = 0?
- azure - Azure 持久函数实体绑定未注册 - node.js