【问题标题】:No database provider has been configured for this DbContext in ASP.NET Core 2.1在 ASP.NET Core 2.1 中没有为此 DbContext 配置数据库提供程序
【发布时间】:2018-11-03 10:36:34
【问题描述】:

我收到此错误:

InvalidOperationException:没有为此 DbContext 配置数据库提供程序。可以通过覆盖 DbContext.OnConfiguring 方法或在应用程序服务提供者上使用 AddDbContext 来配置提供者。如果使用了 AddDbContext,那么还要确保您的 DbContext 类型在其构造函数中接受 DbContextOptions 对象并将其传递给 DbContext 的基本构造函数。

我尝试了一切,但又成功了。我想定义启动连接字符串,但我不能。

我的ApplicationDbContext 是:

public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(){}
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options): base(options){}

    public DbSet<Course> Courses { get; set; }
    public DbSet<CourseType> CourseTypes { get; set; }
    public DbSet<CourseState> CourseStates { get; set; }
    public DbSet<Topic> Topics { get; set; }
    public DbSet<Heding> Hedings { get; set; }
}

我的启动是:

public void ConfigureServices(IServiceCollection services)
{
     services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DbLearning"))));
}

我的appSetting.json 是:

  "ConnectionStrings": {
    "DbLearning": "Server=(localdb)\\mssqllocaldb;Database=DbLearning;Trusted_Connection=True;"
  }

问题是在启动中但在onConfiguring 没有问题

【问题讨论】:

  • 你的 AddDbContext 中的 serviceProvider 是什么?
  • 删除它并更改代码
  • 你也有同样的错误?
  • 是的,正是:(

标签: c# asp.net-mvc entity-framework-6 asp.net-core-2.1


【解决方案1】:

您可以使用最知名的方式使用 localdb

appsetting.json 中的代码

  "ConnectionStrings": {
    "DbLearning": "Server=(localdb)\\mssqllocaldb;Database=DbLearning;Trusted_Connection=True;"
  }

Startup.cs 中的代码

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DbLearning")));
}

【讨论】:

  • 我测试不适合我。再次,我看到了错误并且不在乎
  • 你的机器上安装了什么服务器。
  • LocalDb 安装在你的机器上?
  • 视觉 2017 , sql 2017
【解决方案2】:
"ConnectionStrings": {
  "DbLearning": "Server=(localdb)\\mssqllocaldb;Database=DbLearning;Trusted_Connection=True;"
}

【讨论】:

  • 请添加一些关于此代码如何解决问题的 cmets 以改进此答案。
【解决方案3】:
public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DbLearning")));
}

【讨论】:

    猜你喜欢
    • 2020-06-16
    • 2017-09-02
    • 2019-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-04
    相关资源
    最近更新 更多