繁体   English   中英

在 ASP.NET Core 2.1 中没有为此 DbContext 配置数据库提供程序

[英]No database provider has been configured for this DbContext in ASP.NET Core 2.1

我收到此错误:

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;"
  }

问题是在 startUp 但在onConfiguring没有问题

您可以使用最知名的方式使用 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")));
}
"ConnectionStrings": {
  "DbLearning": "Server=(localdb)\\mssqllocaldb;Database=DbLearning;Trusted_Connection=True;"
}
public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DbLearning")));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM