问题:(使用 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);
来自MSDN;
“SaveChanges 在事务中运行。如果任何脏 ObjectStateEntry 对象无法持久化,SaveChanges 将回滚该事务并引发异常。”
所以似乎没有必要通过TransactionScope.
TransactionScope