dbcontext无法迁移,因为架构不存在?

问题描述

我目前正在编写一些集成测试,这些测试会以不同的模式影响数据库

我正在遵循本指南 https://www.thinktecture.com/en/entity-framework-core/isolation-of-integration-tests-in-2-1/

我的问题是用于创建DbContext的抽象类?

public abstract class IntegrationTestsBase<T> : Idisposable
  where T : DbContext
{
  private readonly string _schema;
  private readonly string _historyTableName;
  private readonly DbContextOptions<T> _options;

  protected T DbContext { get; }

  protected IntegrationTestsBase()
  {
    _schema = Guid.NewGuid().ToString("N");
    _historyTableName = "__EFMigrationsHistory";

    _options = CreateOptions();
    DbContext = CreateContext();
    DbContext.Database.Migrate();
  }

  protected abstract T CreateContext(DbContextOptions<T> options,IDbContextSchema schema);

  protected T CreateContext()
  {
    return CreateContext(_options,new DbContextSchema(_schema));
  }

  private DbContextOptions<T> CreateOptions()
  {
    return new DbContextOptionsBuilder<T>()
        .UseNpgsql($"Server=(local);Database=Demo;...",builder => builder.MigrationsHistoryTable(_historyTableName,_schema))
        .ReplaceService<IMigrationsAssembly,DbSchemaAwareMigrationAssembly>()
        .ReplaceService<IModelCacheKeyFactory,DbSchemaAwareModelCacheKeyFactory>()
        .Options;
  }

  public void dispose()
  {
    DbContext.GetService<IMigrator>().Migrate("0");
    DbContext.Database.ExecutesqlCommand(
           (string)$"DROP TABLE [{_schema}].[{_historyTableName}]");
    DbContext.Database.ExecutesqlCommand((string)$"DROP SCHEMA [{_schema}]");

    DbContext?.dispose();
  }
}

正在创建DbContext,但是一旦调用迁移,我会收到一条错误消息,指出该模式不存在?

我不确定为什么会这样,因为我在自己的配置中确保了

public class SchemaContext : DbContext,IDbContextSchema
{
    public virtual DbSet<Schema>? SchemaModel { get; set; }

    public SchemaContext()
    {
    }

    public SchemaContext(DbContextOptions<SchemaContext> options,IDbContextSchema schema = null)
        : base(options)
    {
        Schema = schema.Schema;
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.HasDefaultSchema(Schema);
        //base.OnModelCreating(modelBuilder);
        modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
    }

    public string Schema { get; }
}

我会假设modelBuilder.HasDefaultSchema(Schema);将创建架构?

这似乎不是事实,因此迁移失败?我想念什么?为什么未在实际数据库中创建模式?

解决方法

如果可以使用仅用于MS SQL的方法-UseSqlServer配置上下文,则必须使用Npgsql.EntityFrameworkCore.PostgreSql包,并使用UseNpgsql扩展方法配置上下文:

.UseNpgsql("Host=localhost;Port=5432;Database=my_db;Username=postgres;Password=password");