What is the best way to acquire an IDbTransaction from an IDbContext?

dapper entity-framework-core

Question

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
4
10/4/2017 1:56:05 PM

Accepted Answer

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;
7
10/4/2017 6:11:14 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow