无法在 EF Core 6 上创建迁移

Unable to create migrations on EF Core 6

我在 运行 dotnet ef migrations add Initial 时遇到了这个问题,我不知道是什么原因造成的。问题是我收到以下错误:

Unable to create an object of type 'ApplicationDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

我把代码翻了一遍又一遍都找不到问题。

这是我的 Program.cs 代码:

using Microsoft.EntityFrameworkCore;
using TrainningManagerService.Context;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
{
    options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString));
});

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

这是我的 ApplicationDbContext:

using Microsoft.EntityFrameworkCore;
using TrainningManagerService.Entities.Database;

namespace TrainningManagerService.Context
{
    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) :
            base(options)
        {
        }

        public DbSet<Video> Videos { get; set; }
        public DbSet<Plan> Plans { get; set; }
    }
}

我已经在 Internet 上遍历了,但在任何地方都找不到解决方案,这真的很困扰我,因为我刚刚创建了一个新的解决方案,但我无法创建一个迁移。

这是由 Program.cs 中的订单引起的。

我必须提高这部分:

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
{
    options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString));
});

于是变成了:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
{
    options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString));
});

var app = builder.Build();

否则构建器在应用数据库之前就已完成