首页 > 解决方案 > 没有为此 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")));

        }

标签: c#asp.net-mvcentity-frameworkdbcontextmembership-provider

解决方案


您需要在 DBContext 下定义实体详细信息,然后才能访问数据库实体,否则您将收到错误消息。因此,请按照以下代码解决此问题。

public CoreContext(DbContextOptions<CoreContext> options): base(options)
{
   public virtual DbSet<Person> Persons { get; set; }
}

推荐阅读