I have a .NET Core app using EF Core. I'm on .NET 8.
I have a bunch of independent contexts declared in C# and F#. The app doesn't know it but the same connection string is injected for all of them. As they all use a schema there are no conflicts and everything runs fine.
The problem arose when I wanted to try and use EnsureCreatedAsync instead of migrating the contexts in my tests.
Since all contexts share the same connection, I can only call EnsureCreatedAsync once. I cannot call it per context as the document is explicit: if there are any tables in the database then no action happens.
I managed to overcome that problem by defining a combined context like that:
public class CombinedDbContext : WriteContextBase
{
private readonly IEnumerable<Action<ModelBuilder>> _onModelCreatings;
public CombinedDbContext(DbContextOptions<CombinedDbContext> options, IEnumerable<Action<ModelBuilder>> onModelCreatings) : base(options, "none") => _onModelCreatings = onModelCreatings;
protected override void OnModelCreating(ModelBuilder modelBuilder) => _onModelCreatings.ToList().ForEach(onModelCreating => onModelCreating(modelBuilder));
}
And here is how I use it:
async Task CreateDatabases(IHost host)
{
aait using var scope = host.Services.CreateScope();
var serviceProvider = scope.ServiceProvider;
var contexts = serviceProvider.GetServices<IMigratableContext>().ToList();
var onModelCreatings = contexts
.Select(context => (Action<ModelBuilder>)context.OnModelCreating)
.ToList();
var combinedDbContext = ActivatorUtilities.CreateInstance<CombinedDbContext>(serviceProvider, onModelCreatings);
await combinedDbContext.Database.EnsureCreatedAsync();
}
I notice that all C# tables are created but not the F# ones.
If I filter onModelCreatings to have only the F# contexts then the F# tables are created.
Does anyone have any idea to why?