无法解决此错误,"No database provider has been configured for this DbContext"

Cannot solve this error, "No database provider has been configured for this DbContext"

经过长时间的休息后,我最近回到了 ASP.Net,并且一直在尝试使用 Core 2.1 开发 Web 应用程序。

我遵循了 Microsoft 网站上的 'beginning' 指南之一,但我在连接到 SQLExpress 的连接字符串的数据提供程序方面遇到了问题。

当我尝试访问 SQLExpress 时,我不断收到错误 "No database provider has been configured for this DbContext"。

完全错误

An unhandled exception occurred while processing the request.
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<TContext> object in its constructor and passes it to the base constructor for DbContext.
Microsoft.EntityFrameworkCore.Internal.DbContextServices.Initialize(IServiceProvider scopedProvider, IDbContextOptions contextOptions, DbContext context)

Stack Query Cookies Headers
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<TContext> object in its constructor and passes it to the base constructor for DbContext.
Microsoft.EntityFrameworkCore.Internal.DbContextServices.Initialize(IServiceProvider scopedProvider, IDbContextOptions contextOptions, DbContext context)
Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
Microsoft.EntityFrameworkCore.DbContext.get_Model()
Microsoft.EntityFrameworkCore.Internal.InternalDbSet<TEntity>.get_EntityType()
Microsoft.EntityFrameworkCore.Internal.InternalDbSet<TEntity>.get_EntityQueryable()
Microsoft.EntityFrameworkCore.Internal.InternalDbSet<TEntity>.System.Linq.IQueryable.get_Provider()
Microsoft.EntityFrameworkCore.RelationalQueryableExtensions.FromSql<TEntity>(IQueryable<TEntity> source, RawSqlString sql, object[] parameters)
SQL_Connection_2.Pages.ContactModel.OnGet() in Contact.cshtml.cs
Microsoft.AspNetCore.Mvc.RazorPages.Internal.ExecutorFactory+VoidHandlerMethod.Execute(object receiver, object[] arguments)
Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.InvokeHandlerMethodAsync()
Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.InvokeNextPageFilterAsync()
Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.Rethrow(PageHandlerExecutedContext context)
Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.InvokeInnerFilterAsync()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Startup.cs

public void ConfigureServices(IServiceCollection services) {
            services.Configure<CookiePolicyOptions>(options => {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddDbContext<ConfigurationContext>(options => {
                options.UseSqlServer(Configuration.GetConnectionString("MyConnection"));
            });
        }

appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "MyConnection": "server=.\SQLExpress;database=WebApp_Test;trusted_connection=true;"
  }
}

ConfigurationContext.cs

public class ConfigurationContext:DbContext {

        public ConfigurationContext() { }
        public ConfigurationContext(DbContextOptions options) : base(options) { }


        public DbSet<Person> Persons { get; set; }

    }

如果我将 ConfigurationContext.cs 中的代码更改为(下方)一切正常,但这是绕过了 appsettings.json 中的连接字符串,所以看起来 services.AddDbContext 似乎不是在 Startup.cs 文件中执行。

public class ConfigurationContext : DbContext {

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
            optionsBuilder.UseSqlServer(@"Server=.\SQLExpress;Database=WebApp_Test;Trusted_Connection=True;MultipleActiveResultSets=true;");
        }

    }

任何人都可以提供有关如何解决此问题的任何建议吗?理想情况下,我希望在 appsettings.json 文件中配置连接字符串。

我花了很多时间试图解决这个问题,寻找那个发现和学习的时刻。

尝试使用您在 OnConfiguring 方法中使用的连接字符串,因为您发布的内容不同。

像这样 -

  "ConnectionStrings": {
    "MyConnection": "Server=.\SQLExpress;Database=WebApp_Test;Trusted_Connection=True;MultipleActiveResultSets=true;"
  }

Startup.cs,加上ConnectionService.Set

public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
        ConnectionService.Set(configuration);
    }

ConnectionService.cs

public static string connstring = "";
public static string Set(IConfiguration config)
    {
        connstring = config.GetConnectionString("MyConnection");
    }

ConfigurationContext.cs

public class ConfigurationContext : DbContext {

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
        optionsBuilder.UseSqlServer(ConnectionService.connstring);
    }

}