'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
?
Solution 1:[1]
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();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |