I'm trying to implement multiple DbContext's targeting the same database.
It works when calling DataBase.EnsureCreated() on the first DbContext object, but it doesnt create tables for the remaining objects. After Init.Initalize() I want the database to contain two tables named Clients and Addresses
Initalize database:
public static class Init
{
public static void Initalize(BaseDbContext[] contexts, Config.Options.Environments environment)
{
if (environment == Config.Options.Environments.Development)
{
contexts[0].Database.EnsureDeleted();
foreach(BaseDbContext context in contexts)
{
context.Database.EnsureCreated();
}
var clients = new Client[]
{
new Client() { Key = Guid.NewGuid(), Name = "Smokers.no", DisplayName = "Smokers.no", Email = "post@smokers.no", LogoFilename = "logo.jpg" }
};
foreach(BaseDbContext context in contexts)
{
if (context.GetType().Equals(typeof(Data.SharedDbContext)))
{
var cntx = context as Data.SharedDbContext;
foreach (Client client in clients) { cntx.Clients.Add(client); }
cntx.SaveChanges();
}
}
}
else
{
foreach(BaseDbContext context in contexts)
{
context.Database.EnsureCreated();
if (context.GetType().Equals(typeof(Data.SharedDbContext)))
{
var cntx = context as Data.SharedDbContext;
if (cntx.Clients.Any())
{
return;
}
}
}
}
}
}
BaseDbContext:
public class BaseDbContext : DbContext
{
public BaseDbContext(DbContextOptions<BaseDbContext> options) : base(options) { }
}
SharedDbContext:
public class SharedDbContext : BaseDbContext
{
public SharedDbContext(DbContextOptions<BaseDbContext> options) : base(options) { }
#region DbSets
public DbSet<Client> Clients { get; set; }
#endregion
}
MailerDbContext:
public class MailerDbContext : BaseDbContext
{
SharedDbContext _context;
public MailerDbContext(DbContextOptions<BaseDbContext> options, SharedDbContext context) : base(options)
{
_context = context;
}
public SharedDbContext LCToolsContext
{
get
{
return _context;
}
}
#region DbSets
public DbSet<Address> Addresses { get; set; }
#endregion
}