gpt4 book ai didi

c# - 无法在 Entity Framework 中捕获 SqlException

转载 作者:太空狗 更新时间:2023-10-30 01:18:45 24 4
gpt4 key购买 nike

我想在删除实体时捕获外键异常。但是 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;
}
}
}

最佳答案

捕获 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;
}
}

关于c# - 无法在 Entity Framework 中捕获 SqlException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25936614/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com