Database.EnsureCreated() force create multiple schemas

Viewed 29

We are using .NET Core 3.1, Microsoft.EntityFrameworkCore v3.1.9 and Npgsql.EntityFrameworkCore.PostgreSQL v3.1.4. We have 2 database schemas and corresponding DbContext files:

schema DbContext
test1 Test1DbContext.cs
test2 Test2DbContext.cs

Test1DbContext.cs:

public partial class Test1DbContext : DbContext
{
    public virtual DbSet<AppModules> AppModules { get; set; }
    public virtual DbSet<AppOffice> AppOffice { get; set; }
    public virtual DbSet<AppRoles> AppRoles { get; set; }
}

Test2DbContext.cs:

public partial class Test2DbContext : DbContext
{
    public virtual DbSet<CacuInter> CacuInter { get; set; }
    public virtual DbSet<Caseevents> Caseevents { get; set; }
    public virtual DbSet<Caseftpses> Caseftpses { get; set; }
}

Database models are defined like this:

[Table("app_modules", Schema = "test1")]
public partial class AppModules
{
    [Key]
    [Column("id")]
    public int Id { get; set; }
    
    [Required]
    [Column("name")]
    [StringLength(25)]
    public string Name { get; set; }
}

When we start integration tests, we want to delete the database and recreate both schemas (test1 and test2). This is the code snippet that we have currently:

private void PrepareDatabase(Test1DbContext test1DbContext, Test2DbContext test2DbContext)
{
    // this drops the *whole* database, not just the `test1` schema
    test1DbContext.Database.EnsureDeleted();
    
    // create `test1` schema
    test1DbContext.Database.EnsureCreated();
    
    // nothing happens here because EF Core thinks that the database has already been created
    test2DbContext.Database.EnsureCreated();
}

We start with test1DbContext.Database.EnsureDeleted() which drops the whole database. Then, we create schema test1 with test1DbContext.Database.EnsureCreated(). At the end, we also want to create schema test2 with test2DbContext.Database.EnsureCreated(), but nothing happens because EF Core thinks that the database has already been created.

How can I force EF Core to create both schemas?

0 Answers
Related