簡體   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