作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
覆盖 System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode) 方法很方便,以便在插入、更新或删除记录时出现暂时性错误(例如死锁或超时)时重试。
我的问题是,在执行 LINQ to SQL 查询时,是否有可以重写的类似函数来处理此类错误?我猜测/希望 DataContext 类中会有一个方法来执行对数据库的实际调用,并且可以重写该方法以执行重试。
我见过的示例(如下所示)通常将 LINQ 表达式和枚举它的方法调用包装在重试 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");
}
我希望避免每次枚举 LINQ 表达式时都必须这样做。此外,通过延迟加载,对数据库的实际调用可以在时间和代码上与 LINQ 表达式很好地分离,因此如果重试可以在较低级别处理会更安全。
最佳答案
您可以通过创建一个为您执行重试的扩展方法来完成它:
public static List<T> ToList_DeadlockRetry<T>(this IEnumerable<T> source, int retryAttempts = 5)
{
while (retryAttempts > 0)
{
try
{
return source.ToList();
}
catch (SqlException ex)
{
retryAttempts--;
if (retryAttempts == 0)
{
throw ex;
}
}
}
}
然后你可以像这样使用它:
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_DeadlockRetry();
关于c# - 在出现暂时性错误时重试 LINQ to SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7155621/
我是一名优秀的程序员,十分优秀!