间歇性 System.Data.Entity.Infrastructure.DbUpdateConcurrencyException

intermittent System.Data.Entity.Infrastructure.DbUpdateConcurrencyException

以下代码导致间歇性异常:

public int UnblockJob(int jobId)
{
    using (var connect = MakeConnect())
    {
        var tag = connect.JobTag.SingleOrDefault(jt => jt.JobId == jobId && jt.Name == Metrics.TagNameItemBlockCaller);
        if (tag == null)
        {
            return 0;
        }
        connect.JobTag.Remove(tag);
        return connect.SaveChanges();
    }
}

如何更正或排除故障?

来自 DbUpdateConcurrencyException 的文档:

Exception thrown by DbContext when it was expected that SaveChanges for an entity would result in a database update but in fact no rows in the database were affected.

这意味着您试图删除的记录已经从数据库中删除。看来您有另一个正在删除记录的进程,或者可以同时调用此函数。

有几种解决方案,这里有几个:

修复源问题停止影响数据的其他进程。

捕获错误将此方法包装在try/catch块中,毕竟您可能只关心记录已被删除:

try
{
    //Existing code here
}
catch(DbUpdateConcurrencyException)
{
    //Safely ignore this exception
}
catch(Exception e)
{
    //Something else has occurred
    throw;
}