Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude DbContext from migrations to avoid Context-Parameter

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.

like image 944
Lion Avatar asked Aug 27 '16 17:08

Lion


1 Answers

Make base class abstract:

public abstract class MySqlContext : DbContext {
    string connectionString;
    // ...
}
like image 77
adem caglin Avatar answered Nov 07 '22 06:11

adem caglin