Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 错误:System.InvalidOperationException:未为此DbContext配置任何数据库提供程序 开头_C#_Entity Framework_Asp.net Core - Fatal编程技术网

C# 错误:System.InvalidOperationException:未为此DbContext配置任何数据库提供程序 开头

C# 错误:System.InvalidOperationException:未为此DbContext配置任何数据库提供程序 开头,c#,entity-framework,asp.net-core,C#,Entity Framework,Asp.net Core,我一直在尝试启动一个小项目,以便学习EF并使用C#创建API。我一直在关注这件事。最初,我在创建初始迁移时遇到了一个问题。这让我找到了。这很有效,我能够创建并运行我的初始迁移。但是,现在每当我尝试调用API路由时,都会出现以下错误: System.InvalidOperationException:未找到任何数据库提供程序 为此DbContext配置。提供程序可以通过以下方式配置: 重写“DbContext.onconfig”方法或使用 应用程序服务提供程序上的“AddDbContext”。如果

我一直在尝试启动一个小项目,以便学习EF并使用C#创建API。我一直在关注这件事。最初,我在创建初始迁移时遇到了一个问题。这让我找到了。这很有效,我能够创建并运行我的初始迁移。但是,现在每当我尝试调用API路由时,都会出现以下错误:

System.InvalidOperationException:未找到任何数据库提供程序 为此DbContext配置。提供程序可以通过以下方式配置: 重写“DbContext.onconfig”方法或使用 应用程序服务提供程序上的“AddDbContext”。如果“AddDbContext” ,然后还要确保DbContext类型接受 DbContextOptions对象,并将其传递给 DbContext的基构造函数。在 Microsoft.EntityFrameworkCore.Internal.DbContextServices.Initialize(IServiceProvider scopedProvider、IDbContextOptions、DbContext context context)
在 Microsoft.EntityFrameworkCore.DbContext.get\u InternalServiceProvider() 在Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()中 在 Microsoft.EntityFrameworkCore.DbContext.Microsoft.EntityFrameworkCore.Internal.IDbContextDependencies.get_EntityFinderFactory() 在Microsoft.EntityFrameworkCore.Internal.InternalDbSet
1.get_Finder()在Microsoft.EntityFrameworkCore.Internal.InternalDbSet
1.FindAsync(对象[]) 在Games.Controllers.GameController.Get(Int32 id)中输入 K:\Projects\c#\Games\Games\Controllers\GameController.cs: lambda_方法5(闭包,对象)在 Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper 映射器,ObjectMethodExecutor,对象控制器,对象[] (a)在 Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g|u waiting | 12_0(ControllerActionInvoker 调用程序,ValueTask`1 actionResultValueTask)位于 Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g|u waiting|10_0(ControllerActionInvoker 调用程序、任务lastTask、状态next、作用域、对象状态、布尔值 完成)在 Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed (上下文)在 Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(状态)& 接下来,在 Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync() ---来自上一个位置的堆栈结束跟踪--位于Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g|u等待| 19_0(ResourceInvoker 调用程序、任务lastTask、状态next、作用域、对象状态、布尔值 完成)在 Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g|u waiting|17_0(ResourceInvoker 调用程序、任务、IDisposable作用域)位于 Microsoft.AspNetCore.Routing.EndpointMiddleware.g|u waitRequestTask | 6|0(端点 端点、任务请求任务、ILogger记录器)位于 Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext (上下文)在 Swashback.AspNetCore.SwaggerUI.SwaggerUI中间件.Invoke(HttpContext httpContext)在 Swashback.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext,ISwaggerProvider(SwiggerProvider)位于 Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext (上下文)

在我开始编写代码之前,我的项目已经设置好,这样我就可以将API项目和数据库项目放在同一个解决方案中。API项目是启动项目,依赖于数据库项目。我也在使用EFCore5.0和.NET5

代码 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; }
    }
}
但是,我在这里遇到的错误是它找不到
migrations.json
。这是因为它正在查找我的API项目的目录,而该文件位于我的数据库项目中

问题 很明显,我在这一切中遗漏了一些非常微妙的东西。可能是快凌晨2点了,咖啡几小时前就喝完了。但我完全被难住了。我会错过什么

编辑 以下是解决方案布局的图片:


在Alexander的一些提示和指导下,我更新了我的函数以更改
目录

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

确保在生成后将
migrations.json
复制到输出文件夹。它来自哪个项目并不重要。然后确保它在应用程序的根文件夹中,而不是在另一个文件夹中。所有配置文件都应与主模块或子文件夹中的某个位置复制到同一文件夹中,从而与主项目(生产中)相关。当然,您需要事先设计文件夹结构,并在代码中对其进行相应配置,以便在运行时查找正确的配置文件。@Alexander:我进行了更新,以便将
migrations.json
转到输出文件夹。该文件位于数据库项目的根文件夹中(但不适用于解决方案或API项目),我仍然收到相同的错误。API项目是否引用数据库项目?我测试了这样的场景,并将从属项目中的文件复制到主项目输出中。另外,您是否正在检查
{root}/bin/Debug/{target}/
文件夹中是否存在文件?确保您正在使用正在查看的某些配置生成项目。@Alexander:是的,API项目引用了数据库项目。我查看了
{root}/bin/Debug/net5.0
,并验证了
迁移.json
确实存在。
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();
            });
        }
    }
}
    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);
    }
    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);
    }