簡體   English   中英

EF Core Add-Migration 因 System.MissingMethodException 失敗:未定義無參數構造函數

[英]EF Core Add-Migration fails with System.MissingMethodException: No parameterless constructor defined

我正在使用 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: No parameterless constructor defined for type 'UserDbContext'。

將無參數構造函數添加到我的上下文結果中:

尚未為此 DbContext 配置數據庫提供程序。 可以通過覆蓋 DbContext.OnConfiguring 方法或在應用程序服務提供者上使用 AddDbContext 來配置提供者。 如果使用 AddDbContext,則還要確保您的 DbContext 類型在其構造函數中接受 DbContextOptions 對象並將其傳遞給 DbContext 的基本構造函數。

我不確定為什么Add-Migration不起作用,如果我需要使用遷移,我不能對 EF 核心使用依賴注入嗎?

問題DbContext在 IOC 中注冊DbContext

更換:

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

和:

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

修復。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM