Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get an IDbTransaction from an IDbContext?

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?

like image 366
Ian Warburton Avatar asked Oct 04 '17 13:10

Ian Warburton


1 Answers

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;

Obsolete: 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();
like image 73
Ivan Stoev Avatar answered Oct 28 '22 11:10

Ivan Stoev