我使用以下代码将单行提交到数据库表(SQL2008/ .NET 4)
using (var db = new MyDbDataContext(_dbConnectionString))
{
Action action = new Action();
db.Actions.InsertOnSubmit(dbAction);
db.SubmitChanges();
}
通常情况下,一切都很好,但偶尔我会遇到以下异常:
System.InvalidOperationException: This SqlTransaction has completed; it is no longer usable.
at System.Data.SqlClient.SqlTransaction.ZombieCheck()
at System.Data.SqlClient.SqlTransaction.Rollback()
at System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode)
上面有许多类似的问题,但我看了之后,找不出原因。
这会不会仅仅是因为SQL超时(异常发生在调用后25秒左右)?或者,在这种情况下,我应该期待SQL超时异常吗?
有没有人知道还有什么原因会导致这种情况?
发布于 2013-05-31 21:49:15
DataContext.SubmitChanges
方法的主体中包含以下代码行:
// ...
try
{
if (this.provider.Connection.State == ConnectionState.Open)
{
this.provider.ClearConnection();
}
if (this.provider.Connection.State == ConnectionState.Closed)
{
this.provider.Connection.Open();
flag = true;
}
dbTransaction = this.provider.Connection.BeginTransaction(IsolationLevel.ReadCommitted);
this.provider.Transaction = dbTransaction;
new ChangeProcessor(this.services, this).SubmitChanges(failureMode);
this.AcceptChanges();
this.provider.ClearConnection();
dbTransaction.Commit();
}
catch
{
if (dbTransaction != null)
{
dbTransaction.Rollback();
}
throw;
}
// ...
当连接超时时,将执行catch
块,并且dbTransaction.Rollback();
行将抛出InvalidOperationException。
如果你对代码有控制权,你可以像这样捕捉异常:
catch
{
// Attempt to roll back the transaction.
try
{
if (dbTransaction != null)
{
dbTransaction.Rollback();
}
}
catch (Exception ex2)
{
// This catch block will handle any errors that may have occurred
// on the server that would cause the rollback to fail, such as
// a closed connection.
Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
Console.WriteLine(" Message: {0}", ex2.Message);
}
throw;
}
发布于 2015-04-22 01:51:50
是!我也有同样的问题。可怕的答案是,SQLServer有时会在遇到错误时在服务器端回滚事务,而不会将错误传递回客户端。呀!
在谷歌"SqlTransaction.ZombieCheck error"组microsoft.public.dotnet.framework.adonet上,Colberd Zhou MSFT很好地解释了这一点。
并查看aef123对this SO post的评论。
发布于 2013-05-26 05:50:35
我可以建议该事务提交的连接更早地关闭。然后回滚该事务。Check this article on MSDN Blog。
https://stackoverflow.com/questions/16692854
复制相似问题