dbContext.Database.BeginTransaction() 自动转换返回类型?

问题描述 投票:0回答:1

我有一个界面:

    public interface IDbTransactionManagerEF: IDbTransactionManager, IDbContextTransaction
    {
    }

当我打电话时

IDbContextTransaction contextTransaction = this._dbContext.Database.BeginTransaction()

我期望得到一个

IDbContextTransaction
类型的值。但
contextTransaction
变量的类型是
SqlServerTransaction

如何将

contextTransaction
转换为
IDbTransactionManagerEF

我做到了:

 this._CommandContextEF.DbTransaction = (IDbTransactionManagerEF)contextTransaction;

但是没有成功,错误显示:

System.InvalidCastException:无法将类型“Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerTransaction”的对象转换为类型“ChainOfCommand.EntityFrameworkCore.IDbTransactionManagerEF”。

与@Nannanas 聊天后,我尝试了这个解决方案但不起作用:

var transactionConverted = (IDbContextTransaction)contextTransaction;
                       this._CommandContextEF.DbTransaction = (IDbTransactionManagerEF)transactionConverted;

错误信息:

Unable to cast object of type 'Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerTransaction' to type 'ChainOfCommand.EntityFrameworkCore.IDbTransactionManagerEF'.
sql-server entity-framework entity-framework-core
1个回答
0
投票

这是一个老问题;但它似乎引起了很大的兴趣。

@quanchinhong 可能一直在寻找这个 GetDbTransaction() 扩展方法:

System.Data.Common.DbTransaction? dbTransaction = transaction.Microsoft.EntityFrameworkCore.Storage.GetDbTransaction();

© www.soinside.com 2019 - 2024. All rights reserved.