I am using EF Core code first in a window service with Autofac DI and when I run Add-Migration TestDD1InitialMigration I get error
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'.
How can I avoid this error?
Thanks in advance
You need a context factory so EF Core can create a DbContext for migrations:
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);
}
}
And an appsettings.json
file where you put your connection string:
{
"ConnectionStrings": {
"DefaultConnection": "<your_connection_string>"
}
}