Three class:
- CustomDbContext
- ReusableContext
- DbContext
Relation:
- ReusableContext : DbContext
- CustomDbContext : ReusableContext
Code:
public class ReusableDbContext : DbContext
{
public ReusableDbContext()
: base("name = myConnectionString")
{
Database.SetInitializer<ReusableDbContext>(new
MigrateDatabaseToLatestVersion<ReusableDbContext, ReusableMigrationsConfiguration>());
}
public DbSet<ReusableTable> ReusableTables{ get; set; }
}
public class ReusableMigrationsConfiguration : DbMigrationsConfiguration<ReusableDbContext>
{
public ReusableMigrationsConfiguration()
: base()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
}
protected override void Seed(ReusableDbContext context)
{
//ReusableMigrationsConfiguration Seed Logic here
// this Seed method is never called ----------- The Problem here!
}
}
then i try to Reuse the ReusableContext like this:
public class CustomDbContext : ReusableDbContext
{
public CustomDbContext()
: base()
{
Database.SetInitializer<CustomDbContext>(new
MigrateDatabaseToLatestVersion<CustomDbContext, CustomMigrationsConfiguration>());
}
public DbSet<CustomTable> CustomTables{ get; set; }
}
public class CustomMigrationsConfiguration : DbMigrationsConfiguration<CustomDbContext>
{
public CustomMigrationsConfiguration()
: base()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
}
protected override void Seed(CustomDbContext context)
{
//CustomMigrationsConfiguration Seed Logic
// this Seed method is called, no problem here
}
}
after running the project:
- ReusableTable and CustomTable are created
- Seed Method of CustomMigrationsConfiguration is called and OK
- BUT, Seed Method of ReusableMigrationsConfiguration is NOT called ——– What is wrong?
Problem solved, here is the solution.
Class:
Relation:
where TContext : ReusableContext
Code:
Now we can Reuse the ReusableContext like this:
after running the project:
all things seem to be fine by now 🙂