c# - EF Core Add-Migration 失败并出现 System.MissingMethodException:未定义无参数构造函数
问题描述
我正在使用 Ef Core 3.1,并且我有以下简单的 DBContext。
public class UserDbContext : DbContext
{
public UserDbContext (DbContextOptions<UserDbContext> options) : base(options)
{
}
public DbSet<User> Users{ get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
}
}
这是我的启动:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();
services.Configure<Settings>(Configuration);
var appSettings = services.BuildServiceProvider().GetService<IOptions<Settings>>().Value;
services.AddDbContext<DbContext>(options =>
options.UseSqlServer(appSettings.DataStoreSettings.ConnectionString));
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetRequiredService<DbContext>();
context.Database.Migrate();
}
}
}
启动我的网站时,仅使用 dbo.__EFMigrationsHistory 表成功创建了数据库。
当我尝试使用以下方法添加迁移时:
Add-Migration Initial -c UserDbContext -Verbose
我收到以下错误:
Microsoft.EntityFrameworkCore.Design.OperationException:无法创建“UserDbContext”类型的对象。有关设计时支持的不同模式,请参阅 https://go.microsoft.com/fwlink/?linkid=851728 ---> System.MissingMethodException:没有为“UserDbContext”类型定义无参数构造函数。
将无参数构造函数添加到我的上下文结果中:
没有为此 DbContext 配置数据库提供程序。可以通过覆盖 DbContext.OnConfiguring 方法或在应用程序服务提供者上使用 AddDbContext 来配置提供者。如果使用了 AddDbContext,那么还要确保您的 DbContext 类型在其构造函数中接受 DbContextOptions 对象并将其传递给 DbContext 的基本构造函数。
我不确定为什么Add-Migration
不工作,如果我需要使用迁移,我不能将依赖注入与 EF 核心一起使用吗?
解决方案
问题在于DbContext
在国际奥委会注册。
更换:
services.AddDbContext<DbContext>(options =>
options.UseSqlServer(appSettings.DataStoreSettings.ConnectionString));
和:
services.AddDbContext<UserDbContext>(options =>
options.UseSqlServer(appSettings.DataStoreSettings.ConnectionString));
解决它。
推荐阅读
- django - 如何创建具有多对多字段的 Django Rest Framework 序列化程序?
- c# - 如何创建多个树视图并将根节点添加到该特定树视图并将这些树视图显示给控件?
- javascript - JavaScript提交按钮功能不起作用
- python - 根据另一列的值过滤一行中的值
- react-hooks - 我应该编译我的反应钩子库,还是只发布 ES6 代码?
- python - 将水平标签与图表中的网格线对齐
- powerbi - 将 Spotfire 中的列转换为 Power BI
- r - 如何重新编码三水平因子
- python - .doc 到 pdf 使用 python 错误
- vue.js - 如何将我的 nuxt 通用应用程序转换为移动原生应用程序