Pass current transaction to DbCommand(将当前事务传递给 DbCommand)
问题描述
我正在开发一个使用 ASP.NET Core 2.1 和 EF Core 2.1 的项目.虽然大部分查询和命令都使用EF,但有些单元需要直接调用存储过程.
I'm working on a project using ASP.NET Core 2.1 and EF Core 2.1. Although most of queries and commands use EF, some units needs to call stored procedures directly.
我不能使用FromSql,因为它需要基于实体模型的结果集.
I can't use FromSql, because it needs results set based on entity models.
假设我们有这些方法:
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
}
}
如果我像这样在一个事务中调用两个命令:
If I call both commands in one transaction like this:
public async Task UnitOfWork(DbContext dbContext)
{
using (var transaction = await dbContext.Database.BeginTransactionAsync())
{
await CommandOne(dbContext);
await CommandTwo(dbContext);
}
}
这个异常会发生:
BeginExecuteReader 要求命令有一个事务,当分配给命令的连接处于挂起的本地事务中.该命令的 Transaction 属性尚未初始化.
BeginExecuteReader requires the command to have a transaction when the connection assigned to the command is in a pending local transaction. The Transaction property of the command has not been initialized.
不得不提,它并不像command.Transaction = ...那么简单.这需要与 EF 使用的事务不同的 DbTransaction.
I have to mention, it's not as simple as command.Transaction = .... This requires DbTransaction which differs from the transaction EF uses.
我已经囤了一个月了!有什么解决方法吗?非常感谢.
I've stocked with this for a month! Is there any workaround for this? Thank you so much.
推荐答案
不得不提,它不像
command.Transaction = ....那么简单,这需要DbTransaction,这与EF使用的事务不同.
I have to mention, it's not as simple as
command.Transaction = ....This requiresDbTransactionwhich differs from the transaction EF uses.
其实是这样的.您只需要参考 Microsoft.EntityFrameworkCore.Relational 程序集并添加
Actually it is. All you need is a reference to Microsoft.EntityFrameworkCore.Relational assembly and add
using Microsoft.EntityFrameworkCore.Storage;
访问 GetDbTransaction 扩展方法:
to get access to GetDbTransaction extension method:
if (context.Database.CurrentTransaction != null)
command.Transaction = context.Database.CurrentTransaction.GetDbTransaction();
这篇关于将当前事务传递给 DbCommand的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将当前事务传递给 DbCommand
基础教程推荐
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
