【问题标题】:Cannot solve this error, "No database provider has been configured for this DbContext"无法解决此错误,“没有为此 DbContext 配置数据库提供程序”
【发布时间】:2020-05-08 17:09:53
【问题描述】:

我最近在休息了很长时间后回到了 ASP.Net,并一直在尝试使用 Core 2.1 进行 Web 应用开发。

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

当我尝试访问 SQLExpress 时,不断收到错误消息“没有为此 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 文件中配置连接字符串。

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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 完美,成功了,谢谢!我确实需要稍作调整...public static void Set(IConfiguration config)
    • 我的荣幸。只要一切正常,您就可以调整任何您喜欢的东西。 :)
    • 我非常不喜欢这个解决方案。为什么要创建一些虚拟服务来仅保存此连接字符串,其中 EF 配置明确指出您应该能够将选项传递给 dbcontexts 构造函数?这段代码只是肮脏和hacky......
    • 然后你发布你的答案。他想将连接字符串从 appsettings.json 传递给 Dbcontext,而他在 Startup.cs 中的 AddDbContext 无法获取。没有别的。
    【解决方案2】:

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

    像这样 -

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

    【讨论】:

      猜你喜欢
      • 2021-05-04
      • 2019-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-02
      • 2019-02-17
      • 2019-10-12
      • 2016-11-15
      相关资源
      最近更新 更多