【发布时间】:2022-01-11 14:51:14
【问题描述】:
这是我第一次尝试使用 EntityFramework 对 DB 进行操作。
我的数据库是在 MySQL 中设置的,所以我已经为它安装了所有需要的 NuGets 包,我试图设置 MySql.EntityFrameworkCore,但是当我尝试运行该程序时,我收到以下错误:
System.AggregateException: '有些服务不能 构造(验证服务描述符时出错 '服务类型:VisualPos.Data.MyDbContext 寿命:范围 ImplementationType:VisualPos.Data.MyDbContext':一个合适的 'VisualPos.Data.MyDbContext' 类型的构造函数不能是 位于。确保类型是具体的并且已注册服务 公共构造函数的所有参数。)'
我的代码如下所示:
程序.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(); ,其中 _context 是 MyDbContext 上下文。
cfg 表还存在于 DB 中。
【问题讨论】:
-
您使用哪些 NuGet 包(用于 MySQL 和 EF Core)和版本?
-
@BradleyGrainger MySql.Data 8.0.27、MySql.EntityFrameworkCore 6.0.0-preview3.1 和 Microsoft.EntityFrameworkCore 6.0.0
标签: c# mysql entity-framework-core .net-6.0