我在GraphQL(min 1.28.22)上关注一个视频,当我运行命令"DotNet ef Migrations Add AddPlatformToDb"时,它返回以下问题:

无法创建类型为‘’的‘DbContext’.try 激活‘CommanderGQL.Data.AppDbContext’时,出现异常‘Unable to解析’Microsoft.EntityFrameworkCore.DbContextOptions`1[CommanderGQL.Data.AppDbContext]‘类型的服务’.‘在try 创建实例时引发.有关设计时支持的不同模式,请参见https://go.microsoft.com/fwlink/?linkid=851728

尽管写了相同的东西,但它并没有在视频中造成任何问题.

CommanderGQL.csproj:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="GraphQL.Server.Ui.Voyager" Version="7.7.1" />
    <PackageReference Include="HotChocolate.AspNetCore" Version="13.9.0" />
    <PackageReference Include="HotChocolate.Data.Entityframework" Version="13.9.0" />
    <PackageReference Include="Microsoft.EntityframeworkCore.Design" Version="8.0.2">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.EntityframeworkCore.SqlServer" Version="8.0.2" />
  </ItemGroup>

</Project>

docker-compose.yaml:

version: '3'
services:
  sqlserver:
    image: "mcr.microsoft.com/mssql/server:2017-latest"
    environment:
      ACCEPT_EULA: "Y"
      SA_PASSWORD: "pa55w0rd!"
      MSSQL_PID: "Express"
    ports:
      - "1433:1433"

appsettings.Development.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "ConnectionStrings": {
    "CommandConStr" : "Server=localhost,1433;Database=CommandsDB;User Id=sa;Password=pa55w0rd!"
  }
}

appsettings.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

Startup.cs:

using CommanderGQL.Data;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

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

        //public IConfiguration Configuration { get; }
        private readonly IConfiguration Configuration;

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<AppDbContext>(opt => opt.UseSqlServer
            (Configuration.GetConnectionString("CommandConStr")));
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // Configure production environment here
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                // Configure endpoints here
            });
        }
    }
}

Platform.cs:

using System.ComponentModel.DataAnnotations;

namespace CommanderGQL.Models
{
    public class Platform
    {
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
        public string LicenseKey { get; set; }
    }
}

AppDbContext.cs:

using CommanderGQL.Models;
using Microsoft.EntityFrameworkCore;

namespace CommanderGQL.Data
{
    public class AppDbContext : DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
        {
        }

        public DbSet<Platform> Platforms { get; set; }
    }
}

Program.cs:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/", () => "Hello World!");

app.Run();

推荐答案

您已经创建了一个使用"新"(自.NET 6起)最小托管模型(自.NET 6模板起使用)的应用程序.你基本上有两个 Select :

  1. 删除Startup.cs并将其内容移到Program.cs文件中,从ConfigureServices开始的所有内容应该在builder.Services上调用(而不是services),从Configure开始的所有内容都应该在app上调用(可能需要我做一些修改):

    builder.Services.AddDbContext<AppDbContext>(opt => opt.UseSqlServer
             (builder.Configuration.GetConnectionString("CommandConStr")));
    // ...
    app.UseDeveloperExceptionPage(); 
    
  2. 重写您的应用程序并切换回可使用Startupgeneric hosting

如果不进行此更改,您在Startup中的代码将不会被应用,因此不会为迁移正确设置上下文.

另见:

Csharp相关问答推荐

C#中的包版本控制

等待限制选项似乎不适用于频道

我可以 suppress 规则CS 9035一次吗?

C#DateTime.ToString在ubuntu和centos中返回不同的结果

REST API端点中异步后台代码执行的类型

内部接口和类的DI解析

如何在实体框架中添加包含列表?

由于POST中的应用程序/JWT,出现不支持的内容类型异常

如何通过属性初始化器强制初始化继承记录内的属性?

在C#中反序列化/序列化具有混合元素顺序的XML时出现问题

TagHelpers在新区域不起作用

.NET 8 DI GetServices<;对象&>不工作

如何在onNext之前等待订阅者完成?

Postgres ENUM类型在第一次运行时对Dapper不可见

在等待OnGetAsync时打开Razor Page显示微调器

如何在Polly重试策略成功之前将HttpClient请求排队?

我想根据姓氏按字母顺序对包含150行徽章编号、姓氏、名字、地址等的文件进行排序.e

DropDownListFor未显示选定值

使用LibraryImport在多个dll中导入相同的函数

分别切换用于读取和写入的EF核心日志(log)