简体   繁体   中英

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

I get this error:

InvalidOperationException: No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.

I tried everything, but right again. I want to define the startup connection string, but I can not.

My ApplicationDbContext is:

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

My StartUp is :

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

My appSetting.json is :

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

The problem is that in startUp but in onConfiguring not problem

You can use the most known way using localdb

Code in appsetting.json

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

Code in 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")));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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