抛出异常:' Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException'在System.Private.CoreLib.ni.dll中

时间:2017-09-18 12:54:51

标签: c# visual-studio api postman

我创建了这个包分配方法:

 [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");
        }


    }

该方法的目的是在邮递员中输入帐户类型,输出应该是具有更新的包类型的用户视图模型。但是,当将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; }
    }

1 个答案:

答案 0 :(得分:1)

鉴于AppUser继承自IdentityUser,似乎在您致电_context.Update(user);时没有Id

我怀疑如果你检查那个字段它将是0,因为它作为身体的一部分进入。

由于这个原因,EF无法找到要更新的实体,这就是您获得异常的原因