内存中 SQLite 上下文引发"无此类表"异常



我尝试使用内存SQLite数据库来改进我的单元测试,我的测试看起来像

[Fact]
public void CreateSampleType()
{
var sampleType = new SampleType("Type One");
var options = new DbContextOptionsBuilder<SamplesContext>()
.UseSqlite("DataSource=:memory:")
.Options;
using (var context = new SamplesContext(options))
{
context.Database.EnsureCreated();
context.SampleType.Add(sampleType);
context.SaveChanges();
};
}

context.SaveChanges();线抛出

Microsoft.Data.Sqlite.SqliteException:SQLite 错误 1:"没有这样的 表:样本类型"。

SamplesContext在连接到 SQL Server 时正常工作。

public class SamplesContext : DbContext
{
public SamplesContext(DbContextOptions<SamplesContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<SampleType>().ToTable("SampleType", schema: "enum").HasKey("Id");
}
public virtual DbSet<SampleType> SampleType { get; set; }
}

我错过了什么? :/

可能需要手动打开连接。此代码示例有效

using (var connection = new SqliteConnection("DataSource=:memory:"))
{
connection.Open();
var options = new DbContextOptionsBuilder<SamplesContext>()
.UseSqlite(connection)
.Options;
using (var context = new SamplesContext(options))
{
context.Database.EnsureCreated();
context.SampleType.Add(sampleType);
context.SaveChanges();
var items = context.SampleType.ToList();
Assert.Single(items);
};
}