我目前正在编写一些集成测试,这些测试只是在一个不同的模式中影响数据库。
我正在遵循这个指南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);已经创建了这个模式?
这似乎不是这种情况,因此迁移失败?我遗漏了什么?为什么没有在实际的数据库中创建模式?
发布于 2020-08-25 19:20:17
在您可以使用仅用于MS UseSqlServer方法配置上下文时,您必须使用Npgsql.EntityFrameworkCore.PostgreSql包并使用UseNpgsql扩展方法配置您的上下文:
.UseNpgsql("Host=localhost;Port=5432;Database=my_db;Username=postgres;Password=password");https://stackoverflow.com/questions/63429975
复制相似问题