MySql.EntityFramework 找不到合适的构造函数

MySql.EntityFramework a suitable constructor could not be located

这是我第一次尝试使用 EntityFramework 对数据库进行操作。

我的数据库设置在 MySQL 中,所以我已经为它安装了所有需要的 NuGets 包,我试图设置 MySql.EntityFrameworkCore 但是当我尝试 运行 程序时我收到以下错误:

System.AggregateException: 'Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: VisualPos.Data.MyDbContext Lifetime: Scoped ImplementationType: VisualPos.Data.MyDbContext': A suitable constructor for type 'VisualPos.Data.MyDbContext' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.)'

我的代码如下所示:

Program.cs

using Microsoft.EntityFrameworkCore;
using VisualPos.Data;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddDbContext<MyDbContext>(options => options.UseMySQL(builder.Configuration.GetConnectionString("Default")));
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build(); // CODE CRASH HERE

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

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

MyDbContext.cs

使用Microsoft.EntityFrameworkCore; 使用 VisualPos.Models;

namespace VisualPos.Data
{
    public class MyDbContext : DbContext
    {
        protected MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
        {
        }
        
        public DbSet<Cfg> Cfg { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

        }
    }
}

然后在我的控制器中我会做 _context.Cfg.ToList(); 其中 _contextMyDbContext 上下文。

数据库中还存在 cfg table。

解决方法在报错信息中:

A suitable constructor for type 'VisualPos.Data.MyDbContext' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.

您的构造函数是 protected。应该是:

public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)