How do I get an IDbTransaction from an IDbContext?

允我心安 提交于 2021-02-08 13:16:41

问题


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

How do I get an IDbTransaction instead of an IDbContextTransaction?


回答1:


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

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;
    }
}

like

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

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;


来源:https://stackoverflow.com/questions/46566756/how-do-i-get-an-idbtransaction-from-an-idbcontext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!