问题:(使用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);
}
UPDATE这适用于回滚和检查,但仍然无法在使用部分内查询:
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);
答案 0 :(得分:15)
来自MSDN;
“SaveChanges在一个事务中运行。如果无法保留任何脏的ObjectStateEntry对象,SaveChanges将回滚该事务并抛出异常。”
所以似乎没有必要通过TransactionScope
明确添加您自己的交易处理。
答案 1 :(得分:7)
在我的情况下,我通过纯SQL从表中删除所有记录,因为EF没有为此提供功能。之后我添加了一些新实体 - 但是当它失败时,表不应该是空的。 我不可能使用MSDTC(TransactionScope)。我将交易减少到DB:
我的代码:
using (var transaction = context.Connection.BeginTransaction())
{
// delete all
base.DeleteAll<TESTEntity>(context);
// add all
foreach (var item in items)
{
context.TESTEntity.AddObject(item);
}
try
{
context.SaveChanges();
transaction.Commit();
return true;
}
catch (Exception ex)
{
Logger.Write("Error in Save: " + ex, "Error");
transaction.Rollback();
return false;
}
}
这里有辅助函数
protected void DeleteAll<TEntity>(ObjectContext context) where TEntity : class
{
string tableName = GetTableName<TEntity>(context);
int rc = context.ExecuteStoreCommand(string.Format(CultureInfo.InvariantCulture, "DELETE FROM {0}", tableName));
}
protected string GetTableName<TEntity>(ObjectContext context) where TEntity : class
{
string snippet = "FROM [dbo].[";
string sql = context.CreateObjectSet<TEntity>().ToTraceString();
string sqlFirstPart = sql.Substring(sql.IndexOf(snippet) + snippet.Length);
string tableName = sqlFirstPart.Substring(0, sqlFirstPart.IndexOf("]"));
return tableName;
}
答案 2 :(得分:5)
我已经能够使用此代码片段解决非常类似的问题:
var connection = new EntityConnection("name=MyEntities");
connection.Open();
var tran = connection.BeginTransaction(System.Data.IsolationLevel.ReadUncommitted);
try
{
var dataContext = new MyEntities(connection);
//CRUD operation1
//CRUD operation2
//CRUD operation3 ...
Assert.AreEqual(expected, actual);
}
catch
{
throw;
}
finally
{
tran.Rollback();
connection.Close();
}
其中MyEntities
是EF DataModel。
关键部分是交易的设定:System.Data.IsolationLevel.ReadUncommitted
使用此隔离级别SQL查询可以读取事务内部所做的更改。
您还需要像我在第一行和第二行那样显式创建连接。
不幸的是,我无法使用TransactionScope
使其工作。