Exclude DbContext from migrations to avoid Context-Parameter

asp.net-core asp.net-core-mvc database-migration ef-code-first entity-framework-core

Question

I'm using ASP.NET EF Core with MySQL (Pomelo.EntityFrameworkCore.MySql driver). Cause such a context need some lines of specific configuration which the default DbContext with MSSQL doesn't have, I created a MySqlContext:

public class MySqlContext : DbContext {
    string connectionString;
    // ...
}

So all my DbContexts are inherited from those class:

public class MyDbContext: MySqlContext {
    public DbSet<MyModel> MyModels{ get; set; }
    // ...
}

In my project I have currently one context (DbContext) which contains DbSets. And the MySqlContext, which isn't a real context like this because it has no DbSets and only acts as a wrapper for the MySQL configuration so that I can better re-use them.

But it seems that the migrations will see them as two different contexts because when I add a migration using command Add-Migration Test I got the error

More than one DbContext was found. Specify which one to use. Use the '-Context' parameter for PowerShell commands and the '--context' parameter for dotnet commands.

So on every migration I have to add -Context MyContext to the command. I would like to avoid this, because as I said the second MySqlContext is not a real context which holds models and migrations. Is there a way to tell the migration tool this? I need something like the [NotMapped] attribute for EF models, which tells EF: Dont store this property to the database. Like this I need to tell EF: Ignore the MySqlContext class cause they need no migrations.

1
7
8/27/2016 5:38:36 PM

Accepted Answer

Make base class abstract:

public abstract class MySqlContext : DbContext {
    string connectionString;
    // ...
}
6
8/27/2016 9:12:04 PM

Popular Answer

The Use-DbContext MyContext command will set MyContext as the default context to use for your PowerShell session. This is another way to avoid having to specify -Context every time.



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