無法使用EF Core Migration

.net autofac c# entity-framework entity-framework-core

我在使用Autofac DI的窗口服務中首先使用EF Core代碼,當我運行Add-Migration TestDD1InitialMigration時出現錯誤

No parameterless constructor was found on 'ClientsContext'. Either add a parameterless constructor to 'ClientsContext' or add an implementation of 'IDbContextFactory<ClientsContext>' in the same assembly as 'ClientsContext'.

我怎樣才能避免這個錯誤?

提前致謝

一般承認的答案

您需要一個上下文工廠,以便EF Core可以為遷移創建DbContext:

public class MyDbContextFactory : IDbContextFactory<MyDbContext>
{
    private IConfigurationRoot _configuration;

    public MyDbContextFactory()
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(System.AppContext.BaseDirectory)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

        _configuration = builder.Build();
    }

    public MyDbContext Create()
    {
        var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
        optionsBuilder.UseSqlServer(_configuration.GetConnectionString("DefaultConnection"), m => { m.EnableRetryOnFailure(); });

        return new MyDbContext(optionsBuilder.Options);
    }
}

以及放置連接字符串的appsettings.json文件:

{
    "ConnectionStrings": {
        "DefaultConnection": "<your_connection_string>"
    }
}


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow