我首先在使用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'.
如何避免此错误?
提前致谢
答案 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>"
}
}