可以很方便地重写 System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode) 方法,以便在插入、更新或删除记录时发生暂时性错误(例如死锁或超时)时重试。
我的问题是,是否有一个类似的函数可以在执行 LINQ to SQL 查询时被重写来处理此类错误?我猜测/希望 DataContext 类中有一个方法可以对数据库进行实际调用,并且可以覆盖该方法以执行重试。
我见过的示例(如下所示)通常将 LINQ 表达式和在重试块中枚举它的方法调用包装起来:
try
{
e.Result = retry.ExecuteAction(() =>
{
Deadlock(); // Artificially create a deadlock condition
CustomerOrdersDataContext ctx = new CustomerOrdersDataContext();
ctx.Connection.ConnectionString = builder.ConnectionString;
ctx.CommandTimeout = 3;
var results = from c in ctx.customers
from o in c.orders
from i in o.order_items
select new { c.lname, c.fname, i.product.product_name, i.quantity };
return results.ToList();
});
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message, "SqlException");
}
}
(来自 http://social.technet.microsoft.com/wiki/contents/articles/retry-logic-for-transient-failures-in-sql-azure.aspx)
我希望以避免每次枚举 LINQ 表达式时都必须执行此操作。此外,通过延迟加载,对数据库的实际调用可能在时间和代码上与 LINQ 表达式很好地分离,因此如果可以在较低级别处理重试会更安全。
It’s convenient to override the System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode) method so that it retries in the event of transient errors, such as deadlocks or timeouts, when inserting, updating or deleting records.
My question is, is there an analogous function that can be overridden to handle such errors when executing a LINQ to SQL query? I’m guessing/hoping there would be a method in the DataContext class that does the actual call to the database and that could be overridden to perform a retry.
The examples I’ve seen (such as shown below) typically wrap the LINQ expression and the method call that enumerates it in a retry block:
try
{
e.Result = retry.ExecuteAction(() =>
{
Deadlock(); // Artificially create a deadlock condition
CustomerOrdersDataContext ctx = new CustomerOrdersDataContext();
ctx.Connection.ConnectionString = builder.ConnectionString;
ctx.CommandTimeout = 3;
var results = from c in ctx.customers
from o in c.orders
from i in o.order_items
select new { c.lname, c.fname, i.product.product_name, i.quantity };
return results.ToList();
});
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message, "SqlException");
}
}
(from http://social.technet.microsoft.com/wiki/contents/articles/retry-logic-for-transient-failures-in-sql-azure.aspx)
I’m hoping to avoid having to do this every time a LINQ expression is enumerated. Furthermore, with delayed loading, the actual call to the database may be well separated in time and code from the LINQ expression, so it would be safer if the retry could be handled at a lower level.
发布评论
评论(1)
您也许可以通过创建一个为您执行重试的扩展方法来完成它:
然后您可以像这样使用它:
You might be able to accomplish it by creating an extension method that performs the retry for you:
Then you could use it like this: