首页 > 解决方案 > 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 核心一起使用吗?

标签: c#entity-framework.net-coreef-core-3.1

解决方案


问题在于DbContext在国际奥委会注册。

更换:

services.AddDbContext<DbContext>(options => 
            options.UseSqlServer(appSettings.DataStoreSettings.ConnectionString));

和:

services.AddDbContext<UserDbContext>(options => 
            options.UseSqlServer(appSettings.DataStoreSettings.ConnectionString));

解决它。


推荐阅读