dotnet / EntityFramework.Docs

Documentation for Entity Framework Core and Entity Framework 6
https://docs.microsoft.com/ef/
Creative Commons Attribution 4.0 International
1.62k stars 1.96k forks source link

Subclassing an Existing DbContext for an Alternate Provider Causes Compilation Errors #2283

Open iUnknwn opened 4 years ago

iUnknwn commented 4 years ago

In Entity Framework Core 3.1, when subclassing an existing DbContext, it will generate an error if you're missing a constructor:

public MySqliteContext(DbContextOptions<MySqliteContext> options) : base(options)

However, this will type error, because the constructor of the base class is expecting type DbContextOptions<MyContext> for options, not DbContextOptions<MySqliteContext>.

This is discussed an in this issue, and the work around is to add a protected constructor in the base class. https://github.com/dotnet/efcore/issues/7533#issuecomment-353669263


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

iUnknwn commented 4 years ago

As a small addendum to this, the once you've made the changes, you still need some code that will register the alternate class to the DI system, otherwise the migration will fail. For an ASP application, something like this would work:

if (_env.IsDevelopment())
{
    services.AddDbContext<MyContext, MySqliteContext>(options =>
            options.UseSqlite(Configuration.GetConnectionString("SqliteConnectionString"))
        );
}

Though you'd also need to set $env:ASPNETCORE_ENVIRONMENT='Development' before running the migration command.