我正在使用 SQLite 数据库文件代替 MS SQL Server 数据库来测试我的 EF 核心应用程序。我遇到了一个问题,因为依赖项注入正在使用新连接传递 dbContext 的新实例,因此当它尝试执行某些操作时(例如创建实体然后尝试发送电子邮件时),我会遇到异常。
The transaction object is not associated with the same connection object as this command.
如何设置我的 Startup.cs,使其仅传递一个连接?
ConfigureServices()
:
if (_env.IsDevelopment())
{
services.AddDbContext<DbContext, InventoryDbContext>(options =>
options.UseSqlite(sqliteConnectionString, o => o.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery))
.AddInterceptors(new QueueSaveChangesInterceptor(), new QueueDbTransactionInterceptor()));
}
else
{
...
Configure()
:
if (env.IsDevelopment())
{
using var scope = app.ApplicationServices.CreateScope();
Application.SetupContext(scope.ServiceProvider);
using var context = scope.ServiceProvider.GetRequiredService<InventoryDbContext>();
context.Database.EnsureDeletedAsync().Wait();
context.Database.EnsureCreatedAsync().Wait();
SqliteDbSeeder.SeedTestDatabase(context);
}
我应该换个方向思考吗?
您可以在
SqliteConnexion
中指定唯一的 UseSqlite
,例如:
var sqliteConnexion = new SqliteConnection(sqliteConnectionString);
services.AddDbContext<DbContext, InventoryDbContext>(
(servicesProvider, options) =>
options.UseSqlite(sqliteConnexion , o => o.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery)
);
您还可以将连接注入为服务,例如:
services.AddSingleton<SqliteConnection>(() => new SqliteConnection(sqliteConnectionString));
services.AddDbContext<DbContext, InventoryDbContext>(
(servicesProvider, options) =>
options.UseSqlite(servicesProvider.GetRequiredService<SqliteConnection>(), o => o.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery)
);