Hel*_* me 5 c# entity-framework
我想在删除实体时捕获外键异常。但是EF仅引发自定义异常。我需要检查是否存在外键冲突,而无需通过EF“手动”检查所有关系。
try
{
applicationDbContext.SaveChanges();
// even though debugger shows an SqlException at first, it doesnt get caught but an DBUpdateException is thrown...
return RedirectToAction("Index");
}
catch (System.Data.SqlClient.SqlException ex)
{
if (ex.Errors.Count > 0)
{
switch (ex.Errors[0].Number)
{
case 547: // Foreign Key violation
ModelState.AddModelError("CodeInUse", "Country code could not be deleted, because it is in use");
return View(viewModel.First());
default:
throw;
}
}
}
Run Code Online (Sandbox Code Playgroud)
捕获DbUpdateException。尝试这个:
try
{
applicationDbContext.SaveChanges();
return RedirectToAction("Index");
}
catch (DbUpdateException e) {
var sqlException = e.GetBaseException() as SqlException;
if (sqlException != null) {
if (sqlException .Errors.Count > 0) {
switch (sqlException .Errors[0].Number) {
case 547: // Foreign Key violation
ModelState.AddModelError("CodeInUse", "Country code could not be deleted, because it is in use");
return View(viewModel.First());
default:
throw;
}
}
}
else {
throw;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6081 次 |
| 最近记录: |