捕获DbUpdateException不会捕获DbUpdateConcurrencyException

时间:2018-10-16 10:49:39

标签: entity-framework-core nlog

我将db.SaveChangesAsync()放在一个try catch块中,如下所示,但是查看日志,我看到了DbUpdateConcurrencyException的日志,但是DbUpdateConcurrencyException源自DbUpdateException

try
{
   await _context.SaveChangesAsync();

}
catch (DbUpdateException)
{
}

但是我注意到以下日志:

Microsoft.EntityFrameworkCore.Update| An exception occurred in the 
database while saving changes for context type 'xxx.MyContext'.
Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException: Database 
operation expected to affect 1 row(s) but actually affected 0 row(s). Data 
may have been modified or deleted since entities were loaded.

我不是通过捕获DbUpdateConcurrencyException来捕获DbUpdateException还是完全错过了异常的工作方式或nlog?

编辑:

我的nlog配置:

<targets>
  <target xsi:type="File" name="all-log" layout="${longdate}|${logger}|${uppercase:${level}} ... />

  <target xsi:type="File" name="own-log" ... />
</targets>

<rules>
   <logger name="*" minlevel="Error" writeTo="all-log" />
   <logger name="Microsoft.*" minlevel="Trace" finale="true" />
   <logger name="*" minlevel="Trace" writeTo="own-log" />
</rules>

1 个答案:

答案 0 :(得分:1)

当您使用ASP.NET Core日志记录时,Microsoft的所有组件都可以写入ASP.NET Core日志记录。 NLog(NLog.Web.AspNetCore)集成还将获取这些日志,因此您可以将其写入文件等。

因此,可能EF组件将该异常写入了日志记录。您可以在配置中使用${stracktrace}${logger}进行检查