Cannot use EF Core Migration

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

Question

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

1
-1
3/29/2017 3:05:12 PM

Accepted Answer

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>"
    }
}
3
3/30/2017 7:04:44 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow