为什么我不能将 ServiceStack OrmLite 中的 IDbTransaction 转换为 DbTransaction? [英] Why can I not cast IDbTransaction in ServiceStack OrmLite to DbTransaction?

查看:35
本文介绍了为什么我不能将 ServiceStack OrmLite 中的 IDbTransaction 转换为 DbTransaction?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ServiceStack.Ormlite v3.9.71 并使用以下代码打开 Ormlite SQLite 事务,假设我想在代码中其他地方的命令中使用此事务:

I am using ServiceStack.Ormlite v3.9.71 and have the following piece of code where I open an Ormlite SQLite Transaction, suppose I want to use this transaction in a command elsewhere in the code:

var connFactory = new OrmLiteConnectionFactory("ConnectionString", SqliteOrmLiteDialectProvider.Instance)
using (IDbConnection db = connFactory.Open()) // using var doesn't make a difference
using (IDbTransaction tran = db.OpenTransaction()) // using var or even db.BeginTransaction() doesn't make a difference
{
    // I do lots of boring stuff
    ...

    // Somewhere else in the code
    using (var cmd = db.CreateCommand())
    {
        cmd.Transaction = tran; // get an error
    }
}    

但是,当我这样做时,我得到了:

however when I do, I get the:

A first chance exception of type 'System.InvalidCastException' occurred in System.Data.dll

Additional information: Unable to cast object of type 'ServiceStack.OrmLite.OrmLiteTransaction' to type 'System.Data.Common.DbTransaction'. 

和堆栈跟踪:

   at System.Data.Common.DbCommand.System.Data.IDbCommand.set_Transaction(IDbTransaction value)

我猜这是由于 OrmLiteTransaction 包装器造成的,我如何才能进行交易?

I guess this is due to the OrmLiteTransaction wrapper, how can I get to the transaction?

推荐答案

OrmLite 提供 ToDbTransaction 扩展方法.

OrmLite provides ToDbTransaction extension method.

public static IDbTransaction ToDbTransaction(this IDbTransaction dbTrans)
    {
        var hasDbTrans = dbTrans as IHasDbTransaction;
        return hasDbTrans != null
            ? hasDbTrans.Transaction
            : dbTrans;
    }

您可以像这样在代码中使用它.

You can use it in your code like this.

cmd.Transaction = tran.ToDbTransaction()

希望它能解决您的问题.

Hope it will solve your problem.

这篇关于为什么我不能将 ServiceStack OrmLite 中的 IDbTransaction 转换为 DbTransaction?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆