将当前事务传递给DbCommand [英] Pass current transaction to DbCommand

查看:199
本文介绍了将当前事务传递给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 = ...那样简单.这要求DbTransaction与EF使用的交易不同.

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 requires DbTransaction which 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;

可以访问

to get access to GetDbTransaction extension method:

if (context.Database.CurrentTransaction != null)
    command.Transaction = context.Database.CurrentTransaction.GetDbTransaction();

这篇关于将当前事务传递给DbCommand的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆