【发布时间】:2017-09-18 22:41:00
【问题描述】:
我创建了这个包分配方法:
[HttpPut("api/auth/user/{id}")]
public async Task<IActionResult> AssignPackage(string id ,[FromBody] AppUser user)
{
try
{
var newUser = Mapper.Map<AppUser, UserViewModel>(user);
var userToEdit = await _context.AppUser
.AsNoTracking()
.SingleOrDefaultAsync(m => m.Id == id);
newUser.PackageType = user.AccountType;
if (userToEdit == null)
{
return NotFound("Could not update user as it was not found");
}
else
{
_context.Update(user);
await _context.SaveChangesAsync();
//return Ok(newUser);
}
UserViewModel _userVM =
Mapper.Map<AppUser, UserViewModel>(user);
return new OkObjectResult(_userVM);
}
catch (DbUpdateException)
{
//Log the error (uncomment ex variable name and write a log.)
ModelState.AddModelError("", "Unable to save changes. " +
"Try again, and if the problem persists, " +
"see your system administrator.");
return NotFound("User not Found");
}
}
该方法的目的是我在 postman 中输入 Account 类型,输出应该是具有更新的 Package Type 的用户视图模型。但是,将 accountType 输入到postman 时,输出为'User not found',错误为'404 Not found'。
在Visual Studio 中显示的错误是问题的标题。不确定问题可能是什么(仅限初学者级别的经验)。
正在使用的模型:
public class AppUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string AccountType { get; set; }
public int? PeriodOrderQty { get; set; }
public int? TotalOrderQty { get; set; }
public Guid? APIKey { get; set; }
public Packages Package { get; set; }
public Cities City { get; set; }
public QualificationLevels Qualifications { get; set; }
public string Token { get; set; }
}
public class UserViewModel
{
public string Id { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public string PackageType { get; set; }
public int? PeriodOrderQty { get; set; }
public int? TotalOrderQty { get; set; }
public Guid? APIKey { get; set; }
}
【问题讨论】:
-
尝试将变量添加到捕获中,即
catch (DbUpdateExecption ex),然后检查该值以查看异常详细信息 -
ex {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. at Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.ThrowAggregateUpdateConcurrencyException(Int32 commandIndex, Int32 expectedRowsAffected, Int32 rowsAffected)在 Catch 异常中中断指向新的 'ex' 变量时,我收到这样的错误。 -
鉴于
AppUser继承自IdentityUser,似乎当您调用_context.Update(user);时没有Id。我怀疑如果您检查该字段,它将为 0,因为它是作为身体的一部分进入的。因此,EF 找不到要更新的实体,这就是您收到异常的原因。 -
当我再次打破指向代码以仔细检查所有实例中的 Id 值作为我传递给邮递员的 Id 返回时,但是还有其他值(如用户名等)仍然为空,可以是因为这个?
-
不太可能。该异常表明数据不再存在于数据库中,或者在调用该方法时无法找到该数据。你试过设置
usertoEdit的值并保存吗?
标签: c# visual-studio api postman