无法使用EF Core Migration

时间:2017-03-29 15:05:12

标签: c# .net entity-framework autofac 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'.

如何避免此错误?

提前致谢

1 个答案:

答案 0 :(得分:3)

您需要一个上下文工厂,以便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>"
    }
}