I need to replace context in WebApplicationFactory. I have MyDbContext which I want to replace with SQLite context for testing.
The replace part works fine
.ConfigureServices(services =>
{
// Remove the app's ApplicationDbContext registration.
var descriptor = services.SingleOrDefault(d => d.ServiceType == typeof(DbContextOptions<MyDbContext>));
if (descriptor != null)
{
services.Remove(descriptor);
}
services.AddDbContext<MyDbContext>(builder =>
{
builder.UseSqlite(CreateInMemoryDatabase());
});
});
But because I moved from Npgsql to SQLite in tests I need to override some default values in OnModelCreating. I created a new db context class
public class MySqlLiteDbContext: MyDbContext
{
public MySqlLiteDbContext(DbContextOptions<MyDbContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Record>()
.Property(b => b.DateCreated)
.HasDefaultValueSql("(datetime('now'))");
...
}
}
Is there any way to inject MySqlLiteDbContext
instead of MyDbContext
to force EnsureCreated use OnModelCreating
for SQLite? Is extracting IMyDbContext
an option? What else can I do to solve this problem?