【发布时间】:2021-01-24 15:36:48
【问题描述】:
如何强制我的 else 语句进入 catch 异常?我得到了这个代码:
try
{
user.UserName = editedUser.Username;
user.Email = editedUser.Email;
user.RowVersion = editedUser.RowVersion;
var result = await userManager.UpdateAsync(user);
if (result.Succeeded)
{
return RedirectToAction("ListOfUsers");
}
else
{
Somehow go to Catch(DbUpdateConcurrencyException ex) // <---------- How?
}
}
catch (DbUpdateConcurrencyException ex)
{
var exceptionEntry = ex.Entries.Single();
var clientValues = (ApplicationUser)exceptionEntry.Entity;
var databaseEntry = exceptionEntry.GetDatabaseValues();
if (databaseEntry == null)
{
ModelState.AddModelError(string.Empty, $"User{editedUser.ID} was deleted before you applied the changes.");
}
else
{
var databaseValues = (ApplicationUser)databaseEntry.ToObject();
if (databaseValues.UserName != clientValues.UserName)
{
ModelState.AddModelError("Username", $"Current username in Database: {databaseValues.UserName}");
}
if (databaseValues.Email != clientValues.Email)
{
ModelState.AddModelError("Email", $"Current email in Database: {databaseValues.Email}");
}
ModelState.AddModelError(string.Empty, "The user you were trying to edit was modified by someone else. Editing operation was canceled and the current values in the database are now shown below. If you still want to edit this user, click Save again, otherwise click Undo");
user.RowVersion = databaseValues.RowVersion;
ModelState.Remove("RowVersion");
}
}
我必须使用 DbUpdateConcurrencyException ex 变量来获取我的数据库条目值。
如果可以在 else 语句中获取这些 db 条目值,我该怎么做?
编辑 - 解决方案: 我发现我们应该避免这种情况并处理代码中的错误,即 if-else,而不是使用 Try/catch。在 else 语句中,我发现了 Identity 使用的异常,并对其进行了处理。并获取数据库值,我使用:
var dbUser = await userManager.Users.AsNoTracking().SingleOrDefaultAsync(x => x.Id == user.Id);
通过这样做,我可以比较“dbUser”和“user”的属性。
【问题讨论】:
-
如果抛出异常,将调用catch语句。所以,你可以
throw new DbUpdateConcurrencyException();,但这似乎有点奇怪。如果您在这种情况下期望的异常没有从对UpdateAsync的调用中抛出,也许您应该跟踪代码并找出为什么您没有收到result.Succeeded。 -
@RufusL 当我这样做时,我的 DbUpdateConcurrencyException ex 变量为空,无法检索我的数据库条目。和 userManager.UpdateAsync(user);失败时不会抛出异常,这就是我使用 if-else 的原因
-
我看不出“手动”输入
catch语句对您有什么好处。我的意思是,您可以只使用throw new DbUpdateConcurrencyException,但它不会被水合,因此您不会从中获得任何有用的信息。UserManager.UpdateAsync返回Task<IdentityResult>的实例,IdentityResult具有Errors的集合。如果result.Succeeded是false,也许你可以使用它。 -
是的,我明白——我应该更清楚一点,我实际上并不是在提倡抛出异常,因为那没有任何意义。您已经声明它在失败时不会抛出异常,那么您为什么期望该异常呢?如果
result不是Succeeded,该类是否没有记录如何确定错误? -
@RufusL 因为我正在尝试进行并发检查,如果 2 个人编辑 RowVersion(); 它将 100% 失败;同时 - 这就是为什么我想对 else 块中的数据库条目做一些事情
标签: c# entity-framework entity-framework-core asp.net-identity