[英]Exception thrown: 'Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException' in System.Private.CoreLib.ni.dll
I created this package assign method: 我创建了这个包分配方法:
[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");
}
}
The aim of the method is that I input the Account type in postman and the output should be the user view model with an updated Package Type. 该方法的目的是我在邮递员中输入Account类型,输出应为具有更新Package类型的用户视图模型。 However when inputting the accountType into
postman
the output is 'User not found'
and the error is '404 Not found'
. 但是,将accountType输入
postman
,输出为'User not found'
和错误为'404 Not found'
。
In Visual Studio
the error being shown is the title of the question. 在
Visual Studio
中,显示的错误是问题的标题。 unsure what the problem may be (only beginner level experience). 不确定可能是什么问题(仅限初学者水平的经验)。
The models being used: 使用的模型:
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; }
}
Given that AppUser
inherits from IdentityUser
it seems that when you call _context.Update(user);
鉴于
AppUser
从IdentityUser
继承,似乎当您调用_context.Update(user);
there is no Id
. 没有
Id
。
I suspect that if you check that field it will be 0, as it's coming in as part of the body. 我怀疑如果您检查该字段,该字段将为0,因为它将作为正文的一部分出现。
EF can't find an entity to update because of this, and that's why you're getting the exception 因此,EF找不到要更新的实体,所以这就是您遇到异常的原因
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.