I am trying to update certain fields of AspNetUser using ASP.NET CORE WEB API using UpdateAsync method. I tried the below but throws an error showing username can't be null. For this case, i want to update phonenumber only.
Controller
    public async Task<IActionResult> UpdateUserAync([FromBody] RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var result = await _userService.UpdateUserAsync(model);
            if (result.IsSuccess)
                return Ok(result);
            return BadRequest(result);
        }
        return BadRequest("Some Properties are not valid!");
    }
Service
  public async Task<UserUpdateResponse>  UpdateUserAsync(RegisterViewModel model)
    {
        var user = await _userManager.FindByEmailAsync(model.Email);
        var phoneNumber = await _userManager.GetPhoneNumberAsync(user);
        if (user == null)
            throw new NullReferenceException("Update model is null");
        if (phoneNumber!=null)
            return new UserUpdateResponse
            {
                Message = "Sorry you can't update!",
                IsSuccess = false,
            };
        var identityUser = new IdentityUser
        {
            PhoneNumber = model.PhoneNumber
    };
        var result = await _userManager.UpdateAsync(identityUser);
        if (result.Succeeded)
        {
            return new UserUpdateResponse
            {
                Message = "Phone number updated Successfully",
                IsSuccess = true,
                Errors = result.Errors.Select(e => e.Description)
            };
        }
        return new UserUpdateResponse
        {
            Message = "Phone number didnot Updated!",
            IsSuccess = false,
            Errors = result.Errors.Select(e => e.Description)
        };
    }
Here, I only want to update certain fields based on user email/user id.
ErrorMSG
{
"message": "Phone number didnot Updated!",
"isSuccess": false,
"errors": [
    "User name '' is invalid, can only contain letters or digits."
],
"expireDate": null
}
 
                        
Entity Framework tries to
INSERTthis user, notUPDATEit as you create a new instance ofIdentityUser:So this is the reason why you've got the error. To
UPDATEthe user, you need updateuserthat you've found byFindByEmailAsyncmethod: