如何从IDbContext获取IDbTransaction? [英] How do I get an IDbTransaction from an IDbContext?

查看:102
本文介绍了如何从IDbContext获取IDbTransaction?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个 IDbContext 具有一个 DatabaseFacade ,该数据库具有一个 CurrentTransaction 属性.但是 CurrentTransaction IDbContextTransaction .我想将 IDbTransaction 传递给Dapper.

An IDbContext has a DatabaseFacade, which has a CurrentTransaction property. But the CurrentTransaction is an IDbContextTransaction. I want to pass an IDbTransaction to Dapper.

如何获取 IDbTransaction 而不是 IDbContextTransaction ?

推荐答案

当前(当前是EF Core 2.0的最新版本)没有官方的方法.

Currently (up to latest at this time EF Core 2.0) there is no official way to do that.

但是您可以使用以下自定义扩展方法从 IDbContextTransaction 中获取它:

But you can use the following custom extension method to get it from IDbContextTransaction:

using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage;
using System.Data.Common;

public static class EFExtensions
{
    public static DbTransaction GetDbTransaction(this IDbContextTransaction source)
    {
        return (source as IInfrastructure<DbTransaction>).Instance;
    }
}

喜欢

var dbTransaction = context.Database.CurrentTransaction.GetDbTransaction();

更新:实际上,EF Core提供了具有上述签名的扩展方法.它由 DbContextTransactionExtensions 提供> 类.为了使用它,您只需要引用 Microsoft.EntityFrameworkCore.Relational.dll 程序集和

Update: Actually EF Core provides extension method with the above signature out of the box. It's provided by the DbContextTransactionExtensions class. In order to use it, all you need is a reference to Microsoft.EntityFrameworkCore.Relational.dll assembly and

using Microsoft.EntityFrameworkCore.Storage;

这篇关于如何从IDbContext获取IDbTransaction?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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