-
Notifications
You must be signed in to change notification settings - Fork 4
Support multiple DbContexts in integration tests #123
Copy link
Copy link
Open
Labels
bugSomething isn't workingSomething isn't working
Milestone
Description
Currently, we do this in DbContextsInitializer:
foreach (var ctx in getContexts())
{
await CreatePolicy.ExecuteAsync(async () =>
{
await ctx.Database.EnsureDeletedAsync(); // This is the culprit
await ctx.Database.EnsureCreatedAsync();
});
}Unfortunately, if you add multiple DbContexts, every one loop will delete and re-create the database (with different schema!) because we use single connection string. This makes it unusable in multi-context systems. There is a workaround that just overrides the registered context (in TestOverridesPostModule pattern), like:
public override void ConfigureServices(IServiceCollection services)
{
var oldCtx = services
.Where(c =>
c.ServiceType == typeof(ClientsDbContext) ||
c.ServiceType == typeof(DbContextPool<ClientsDbContext>) ||
c.ServiceType == typeof(DbContextPool<ClientsDbContext>.Lease) ||
c.ServiceType == typeof(DbContextOptions<ClientsDbContext>))
.ToList();
foreach (var c in oldCtx)
{
services.Remove(c);
}
var dbConnStr = Api.Config.ConnectionStrings.Database(config);
var builder = new SqlConnectionStringBuilder(dbConnStr);
builder.InitialCatalog += "_clients";
services.AddDbContext<ClientsDbContext>(options =>
{
options.UseSqlServer(builder.ToString(), sqlOpts => sqlOpts.MigrationsAssembly("XYZ.Migrations"));
options.EnableSensitiveDataLogging();
});
}but that is suboptimal.
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
bugSomething isn't workingSomething isn't working