问题
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