当从MySQL数据库中删除与其他表相关的对象时,捕获DbUpdateException时出现问题,并且DbContext.SaveChanges()会引发该确切异常。
以下代码未捕获异常:
public async Task<ActionResult<JobTitle>> DeleteJobtitle(int id) {
var jobtitle = await _context.Jobtitle.FindAsync(id);
if (jobtitle == null) {
return NotFound();
}
_context.Jobtitle.Remove(jobtitle);
try {
_context.SaveChanges();
}
catch (DbUpdateException ex) {
Console.WriteLine("exception: " + ex.Message);
}
return jobtitle;
}
这是发生异常时的控制台输出:
Microsoft.EntityFrameworkCore.Database.Command[20102]
Failed executing DbCommand (1,601ms) [Parameters=[@p0='?' (DbType = Int32)], CommandType='Text', CommandTimeout='30']
DELETE FROM `jobtitle`
WHERE `idJobTitle` = @p0;
SELECT ROW_COUNT();
fail: Microsoft.EntityFrameworkCore.Update[10000]
An exception occurred in the database while saving changes for context type 'DbAPI.DbContexts.DbContext'.
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details.
为什么我的try catch块无法捕获异常?