小编典典

实体框架:使用事务和回滚......可能吗?

all

问题:(使用 Sql 2005)

  • 事务启动时如何查询数据库?(因为它锁定了桌子)
  • 如何使事务回滚然后关闭自身以允许查询表?

所以我发现了这么多:

[TestMethod]
public void CreateUser()
{
    TransactionScope transactionScope = new TransactionScope();

    DataContextHandler.Context.AddToForumUser(userToTest);
    DataContextHandler.Context.SaveChanges();

    DataContextHandler.Context.Dispose();
}

DataContextHandler 只是一个简单的单例,它为我的实体公开上下文对象。这似乎正如你所想的那样工作。它创建用户,保存,然后在程序结束时回滚。(IE测试结束)

问题:如何强制事务回滚并杀死自己,以便查询表?

原因:出于测试目的,我想确保用户:

  • 已保存
  • 可以正确查询证明其存在
  • 已删除(垃圾数据)
  • 可以查询以确保它已被删除。

截至目前,如果测试结束,我只能让事务回滚,并且我无法弄清楚如何查询事务:

[TestMethod]
public void CreateUser()
{
    ForumUser userToTest = new ForumUser();

    TransactionScope transactionScope = new TransactionScope();

    DataContextHandler.Context.AddToForumUser(userToTest);
    DataContextHandler.Context.SaveChanges();     

    Assert.IsTrue(userToTest.UserID > 0);

    var foundUser = (from user in DataContextHandler.Context.ForumUser
                    where user.UserID == userToTest.UserID
                    select user).Count();  //KABOOM Can't query since the 
                                           //transaction has the table locked.

    Assert.IsTrue(foundUser == 1);

    DataContextHandler.Context.Dispose();

    var after = (from user in DataContextHandler.Context.ForumUser
                 where user.UserID == userToTest.UserID
                 select user).Count(); //KABOOM Can't query since the 
                                       //transaction has the table locked.

    Assert.IsTrue(after == 0);
}

更新这适用于回滚和检查,但仍然无法在 using 部分中查询:

using(TransactionScope transactionScope = new TransactionScope())
{
    DataContextHandler.Context.AddToForumUser(userToTest);
    DataContextHandler.Context.SaveChanges();
    Assert.IsTrue(userToTest.UserID > 0);
    //Still can't query here.

}

var after = (from user in DataContextHandler.Context.ForumUser
            where user.UserID == userToTest.UserID
            select user).Count();

Assert.IsTrue(after == 0);

阅读 121

收藏
2022-06-01

共1个答案

小编典典

来自MSDN

“SaveChanges 在事务中运行。如果任何脏 ObjectStateEntry 对象无法持久化,SaveChanges 将回滚该事务并引发异常。”

所以似乎没有必要通过TransactionScope.

2022-06-01