[英]Pass current transaction to DbCommand
我正在使用ASP.NET Core 2.1和EF Core 2.1开发一个项目。 虽然大多数查询和命令都使用EF,但某些单元需要直接调用存储过程。
我不能使用FromSql ,因为它需要基于实体模型的结果集。
我们假设我们有这些方法:
public Task CommandOne(DbContext context)
{
Entity entity = new Entity
{
Name = "Name"
};
context.DbSet<Entity>().Add(entity);
return context.SaveChangesAsync();
}
public async Task CommandTwo(DbContext context)
{
DbCommand command = context.Database.GetDbConnection().CreateCommand();
command.CommandText = "storedProcName";
command.CommandType = System.Data.CommandType.StoredProcedure;
using (var reader = await command.ExecuteReaderAsync().ConfigureAwait(false))
{
// read result sets
}
}
如果我在一个事务中调用这两个命令,如下所示:
public async Task UnitOfWork(DbContext dbContext)
{
using (var transaction = await dbContext.Database.BeginTransactionAsync())
{
await CommandOne(dbContext);
await CommandTwo(dbContext);
}
}
这个例外将会发生:
当分配给命令的连接处于挂起的本地事务中时,BeginExecuteReader要求该命令具有事务。 该命令的Transaction属性尚未初始化。
我不得不提一下,它不像command.Transaction = ...
那么简单。 这需要DbTransaction
,它与EF使用的事务不同。
我已经放了一个月了! 这有什么解决方法吗? 非常感谢。
我不得不提一下,它不像
command.Transaction = ....
这需要DbTransaction
,它与EF使用的事务不同。
实际上是。 您只需要参考Microsoft.EntityFrameworkCore.Relational程序集并添加
using Microsoft.EntityFrameworkCore.Storage;
访问GetDbTransaction
扩展方法:
if (context.Database.CurrentTransaction != null)
command.Transaction = context.Database.CurrentTransaction.GetDbTransaction();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.