How can I use TransactionScope with SQL Compact 4.0 and NHibernate

血红的双手。 提交于 2019-12-24 00:07:09

问题


I am trying to use NHibernate in combination with .NET's TransactionScope object. So far I have successfully used Oracle 11g and SQL Server 2008R2 with no issues. However, SQL Compact seems to fall on its face.

using (var scope = new TransactionScope(TranactionScopeOption.Required))
{
    using (var session = _sessionFactory.OpenSession())
    {
        // The line below throws.  I also tried passing in System.Data.IsolationLevel.ReadCommitted to no avail
        using (var txn = session.BeginTransaction())
        {
            // Perform insert
            txn.Commit();
        }
    }
    scope.Complete();
}

This results in the following exception. I understand what this means, but I don't understand why it is attempting to create a nested transaction.

NHibernate.TransactionException: Begin failed with SQL exception ---> System.InvalidOperationException: SqlCeConnection does not support nested transactions.
   at System.Data.SqlServerCe.SqlCeConnection.BeginTransaction(IsolationLevel isolationLevel)
   at System.Data.SqlServerCe.SqlCeConnection.BeginDbTransaction(IsolationLevel isolationLevel)
   at System.Data.Common.DbConnection.System.Data.IDbConnection.BeginTransaction(IsolationLevel isolationLevel)
   at NHibernate.Transaction.AdoTransaction.Begin(IsolationLevel isolationLevel)
       at NHibernate.Transaction.AdoTransaction.Begin(IsolationLevel isolationLevel)

回答1:


Your code potentially produces 2 transactions:

1)new TransactionScope(TranactionScopeOption.Required)
2)session.BeginTransaction()

TransactionScope.Required "uses an ambient transaction if one already exists. Otherwise, it creates a new transaction before entering the scope. This is the default value". Your are guaranteed to have an ambient transaction by time session.BeginTransaction() gets hit, hence, making it a nested transaction.

If the transaction scope is not completed everything within its scope will be rolled back.




回答2:


I think the answer lies in this question: The connection object can not be enlisted in transaction scope

"At a guess, TransactionScope needs to escalate to a distributed or nested transaction, neither of which is supported by CE."



来源:https://stackoverflow.com/questions/8127735/how-can-i-use-transactionscope-with-sql-compact-4-0-and-nhibernate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!