相关疑难解决方法(0)

TransactionScope如何回滚交易?

我正在编写一个集成测试,我将把一些对象插入数据库,然后检查以确定我的方法是否检索这些对象.

我与数据库的连接是通过NHibernate ...而我创建这样一个测试的常用方法是执行以下操作:

NHibernateSession.BeginTransaction();

//use nhibernate to insert objects into database
//retrieve objects via my method
//verify actual objects returned are the same as those inserted

NHibernateSession.RollbackTransaction();
Run Code Online (Sandbox Code Playgroud)

但是,我最近发现了TransactionScope,它显然可以用于这个目的......

我发现的一些示例代码如下:

public static int AddDepartmentWithEmployees(Department dept)
{

    int res = 0;

    DepartmentAdapter deptAdapter = new DepartmentAdapter();
    EmployeeAdapter empAdapter = new EmployeeAdapter();
    using (TransactionScope txScope = new TransactionScope())
    {

        res += deptAdapter.Insert(dept.DepartmentName);
        //Custom method made to return Department ID 
        //after inserting the department "Identity Column"
        dept.DepartmentID = deptAdapter.GetInsertReturnValue(); …
Run Code Online (Sandbox Code Playgroud)

.net c# nhibernate transactions transactionscope

95
推荐指数
2
解决办法
9万
查看次数

TransactionScope和Transactions

在我的C#代码中,我使用TransactionScope,因为我被告知不要依赖我的sql程序员将始终使用事务,我们负责和yada yada.

话说回来

它看起来像TransactionScope对象在SqlTransaction之前回滚?这是可能的,如果是这样,在事务中包装TransactionScope的正确方法是什么.

这是sql测试

CREATE PROC ThrowError
AS

BEGIN TRANSACTION --SqlTransaction
SELECT 1/0

IF @@ERROR<> 0
BEGIN
  ROLLBACK TRANSACTION --SqlTransaction
  RETURN -1 
END
ELSE
BEGIN
  COMMIT TRANSACTION --SqlTransaction
  RETURN 0
END

go

DECLARE @RESULT INT

EXEC @RESULT = ThrowError

SELECT @RESULT
Run Code Online (Sandbox Code Playgroud)

如果我运行这个,我得到除以0并返回-1

从C#代码调用我得到一个额外的错误消息

遇到零除错误.
EXECUTE之后的事务计数表示缺少COMMIT或ROLLBACK TRANSACTION tatement.先前的计数= 1,当前计数= 0.

如果我给sql事务一个名字然后

无法回滚SqlTransaction.未找到该名称的任何事务或保存点.EXECUTE之后的事务计数表示缺少COMMIT或ROLLBACK TRANSACTION语句.先前的计数= 1,当前计数= 2.

有时似乎计数上升,直到应用程序完全退出

c#就是这样

        using (TransactionScope scope = new TransactionScope())
        {
             ... Execute Sql 

             scope.Commit()
         }
Run Code Online (Sandbox Code Playgroud)

编辑:

sql代码必须适用于2000和2005

c# sql transactions

17
推荐指数
2
解决办法
2万
查看次数

标签 统计

c# ×2

transactions ×2

.net ×1

nhibernate ×1

sql ×1

transactionscope ×1