简体   繁体   English

错误:System.InvalidOperationException:没有为此 DbContext 配置数据库提供程序

[英]ERROR: System.InvalidOperationException: No database provider has been configured for this DbContext

THE BEGINNING开始

I've been trying to get a small project started so I can learn EF and creating APIs using C#.我一直在尝试启动一个小项目,这样我就可以学习 EF 并使用 C# 创建 API。 I'm following this tutorial for the API and followed this tutorial for EF setup .我正在关注API 的本教程,并遵循EF 设置的本教程 Initially, I was running across an issue creating my initial migration.最初,我在创建初始迁移时遇到了问题。 This lead to me finding about creating a DbContextFactory .这导致我发现有关创建 DbContextFactory 的信息 That worked, and I was able to create and run my initial migration.那行得通,我能够创建并运行我的初始迁移。 Now, however, I'm getting this error whenever I try calling my API route:但是,现在,每当我尝试调用我的 API 路由时,都会收到此错误:

System.InvalidOperationException: No database provider has been configured for this DbContext. System.InvalidOperationException:没有为此 DbContext 配置数据库提供程序。 A provider can be configured by overriding the 'DbContext.OnConfiguring' method or by using 'AddDbContext' on the application service provider.可以通过覆盖“DbContext.OnConfiguring”方法或在应用程序服务提供程序上使用“AddDbContext”来配置提供程序。 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.如果使用了“AddDbContext”,那么还要确保您的 DbContext 类型在其构造函数中接受 DbContextOptions object 并将其传递给 DbContext 的基本构造函数。 at Microsoft.EntityFrameworkCore.Internal.DbContextServices.Initialize(IServiceProvider scopedProvider, IDbContextOptions contextOptions, DbContext context)在 Microsoft.EntityFrameworkCore.Internal.DbContextServices.Initialize(IServiceProvider scopedProvider,IDbContextOptions contextOptions,DbContext 上下文)
at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider() at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies() at Microsoft.EntityFrameworkCore.DbContext.Microsoft.EntityFrameworkCore.Internal.IDbContextDependencies.get_EntityFinderFactory() at Microsoft.EntityFrameworkCore.Internal.InternalDbSet 1.get_Finder() at Microsoft.EntityFrameworkCore.Internal.InternalDbSet 1.FindAsync(Object[] keyValues) at Games.Controllers.GameController.Get(Int32 id) in K:\Projects\c#\Games\Games\Controllers\GameController.cs:line 23 at lambda_method5(Closure, Object ) at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 在 Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider() 在 Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies() 在 Microsoft.EntityFrameworkCore.DbContext.Microsoft.EntityFrameworkCore.Internal.IDbContextDependencies.get_EntityFinderFactory() 在 Microsoft.EntityFrameworkCore.Internal.InternalDbSet 1.get_Finder() at Microsoft.EntityFrameworkCore.Internal.InternalDbSet 1.FindAsync(Object[] keyValues) 在 Games.Controllers.GameController.Get(Int32 id) 在 K:\Projects\c#\Games\Games\Controllers\GameController.cs:line 23 at lambda_method5(Closure, Object ) at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|12_0 (ControllerActionInvoker 调用程序,ValueTask`1 actionResultValueTask) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync() --- End of stack trace from previous location --- at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Z5D113F2038 actionResultValueTask) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context ) 在 Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) 在 Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker 的堆栈跟踪中的堆栈跟踪 () --- 在 Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|19_0(ResourceInvoker 调用程序,任务 lastTask,State 下一个,Z5D113F2038 D289F391614C39043629E8Z scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) at Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext) at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider) at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context) D289F391614C39043629E8Z scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) at Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) 在 Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) 在 Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext) 在 Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext) http,在 Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext 上下文)

Before I get to the code, my project is setup so that I have the API project and the Database project in the same solution.在我开始编写代码之前,我的项目已设置好,以便在同一个解决方案中拥有 API 项目和数据库项目。 The API project is the start up project, and is dependent on the Database project. API 项目是启动项目,依赖于数据库项目。 I'm also using EF Core 5.0 and .NET 5.我也在使用 EF Core 5.0 和 .NET 5。

THE CODE编码

GameDbContext.cs GameDbContext.cs

using Games.Db.Tables;
using Microsoft.EntityFrameworkCore;

namespace Games.Db
{
    public class GameDbContext : DbContext
    {
        public GameDbContext(DbContextOptions<GameDbContext> options) : base(options)
        {

        }

        public DbSet<Game> Game { get; set; }
        public DbSet<Platform> Platform { get; set; }
        public DbSet<Medium> Medium { get; set; }
    }
}

GameDbContextFactory.cs GameDbContextFactory.cs

using System.IO;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;

namespace Games.Db
{
    public class GameDbContextFactory : IDesignTimeDbContextFactory<GameDbContext>
    {
        public GameDbContext CreateDbContext(string[] args)
        {
            var configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("migrations.json")
                .Build();
            var optionsBuilder = new DbContextOptionsBuilder<GameDbContext>();
            var connectionString = configuration.GetConnectionString("MigrationsHelperConnection");
            optionsBuilder.UseSqlServer(connectionString);

            return new GameDbContext(optionsBuilder.Options);
        }
    }
}

Startup.cs启动.cs

using Games.Db;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;

namespace Games
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddDbContext<GameDbContext>();

            services.AddTransient<DbContext, GameDbContext>();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "Games", Version = "v1" });
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Games v1"));
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

WHAT I TRIED我尝试了什么

I found this question , and added the OnConfiguring() to my GameDbContext, and created this:我发现了这个问题,并将OnConfiguring()添加到我的 GameDbContext 中,并创建了这个:

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        var directory = Directory.GetCurrentDirectory();
        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("migrations.json")
            .Build();
        var connectionString = configuration.GetConnectionString("MigrationsHelperConnection");
        optionsBuilder.UseSqlServer(connectionString);
    }

However, the error I get at this point is that it can't find the migrations.json .但是,我此时得到的错误是它找不到migrations.json This is because it's looking the directory of my API project, and the file is in my Database project.这是因为它正在查找我的 API 项目的目录,并且该文件在我的数据库项目中。

THE QUESTION问题

I'm obviously missing something very subtle in all this.我显然在这一切中遗漏了一些非常微妙的东西。 Could be that it's almost 2am and the coffee ran out hours ago.可能是将近凌晨 2 点,咖啡在几个小时前就用完了。 But I'm completely stumped.但我完全被难住了。 What could I be missing?我会错过什么?

EDIT编辑

Here's a picture of solution layout:这是解决方案布局的图片:

在此处输入图像描述

After some prompting and guiding from Alexander, I updated my function to change the Directory :在 Alexander 的一些提示和指导下,我更新了我的 function 以更改Directory

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        var directory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); 
        var configuration = new ConfigurationBuilder()
            .SetBasePath(directory)
            .AddJsonFile("migrations.json")
            .Build();
        var connectionString = configuration.GetConnectionString("MigrationsHelperConnection");
        optionsBuilder.UseSqlServer(connectionString);
    }

暂无
暂无

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

相关问题 System.InvalidOperationException:没有为此DbContext配置数据库提供程序 - System.InvalidOperationException: No database provider has been configured for this DbContext InvalidOperationException:没有为此DbContext配置数据库提供程序 - InvalidOperationException: No database provider has been configured for this DbContext InvalidOperationException:没有为此 DbContext 配置具有存储库模式的数据库提供程序 - InvalidOperationException: No database provider has been configured for this DbContext with Repository pattern InvalidOperationException:没有为此DbContext配置数据库提供程序。 - InvalidOperationException: No database provider has been configured for this DbContext. InvalidOperationException:没有为此DbContext配置数据库提供程序。 可以通过覆盖DbContext来配置提供程序 - InvalidOperationException: No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext add-Migration 错误 没有为此 DbContext 配置数据库提供程序 - add-Migration Error No database provider has been configured for this DbContext 添加迁移错误:尚未为此DbContext配置数据库提供程序 - Add migration error: No database provider has been configured for this DbContext 错误提示。没有为此 DbContext 配置数据库提供程序 - Error saying.No database provider has been configured for this DbContext 无法解决此错误,“尚未为此 DbContext 配置数据库提供程序” - Cannot solve this error, "No database provider has been configured for this DbContext" ASP.NET核心InvalidOperationException:&#39;尚未为此DbContext配置数据库提供程序。 - ASP.NET core InvalidOperationException: 'No database provider has been configured for this DbContext./
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM