使用存储库-服务-控制器架构更新我的 CRUD 中的功能

问题描述 投票:0回答:1

我的用户实体有存储库层、服务层和控制器层。我想通过用户名更新我的记录之一。 这是我的更新存储库层:

 public async Task<entities.User> UpdateUserAsync(entities.User entity)
 {

  _dbContext.Users.Update(entity);
  await _dbContext.SaveChangesAsync();
  return entity;
 }
   public async Task<entities.User> GetUserAsync(string userName)
  {
   var result = await _dbContext.Users.FirstOrDefaultAsync(x => x.UserName == 
   userName);
   return result;
 }

现在我在Service层使用我的更新方法:

    public async Task UpdateUserAsync(UserUpdateRequestDto dto)
     {
 

     var user = await _userRepository.GetUserAsync(dto.UserName);
     if (user == null)
     {
         throw new Exception("User not found.");
     }
 
 user.Email = dto.Email ?? user.Email;
 user.Name = dto.Name ?? user.Name;
 user.Family = dto.Family ?? user.Family;
 user.Password = dto.Password ?? user.Password;
 user.ConfirmPassword = dto.ConfirmPassword ?? user.ConfirmPassword;
 user.RoleId = dto.RoleId != 0 ? dto.RoleId : user.RoleId;

 await _userRepository.UpdateUserAsync(user);

现在这是我的此功能的控制器部分:

    [HttpPut]
    [Route("update-user")]
    public async Task<IActionResult> UpdateUserAsync(UserUpdateRequestDto dto)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);  
        }
        try
        {
            await _userService.UpdateUserAsync(dto);
            
            return Ok("User updated successfully.");
        }
        catch (Exception ex)
        {
            return BadRequest(ex.Message);
        }
    }  
My problem is when I tried my update function with swagger,it updates my record but it shows string value for all fields and If I enter username and a value for other fields ,it updates but change the other records to string in database.How can I fix this problem to solve this?
c# asp.net crud
1个回答
0
投票

Swagger UI 将使用默认值来指示您将在何处输入值,因此它很可能将这些值作为文字发送

"string"
。为了快速修复,您应该在发送请求之前删除查询正文中显示字符串的默认值。作为附加的安全措施,您还可以忽略您认为无效输入的值。像这样的东西,这样空字符串或空值就不会覆盖你的列:

user.Email = !string.IsNullOrWhitespace(dto.Email) ? dto.Email : user.Email;
© www.soinside.com 2019 - 2024. All rights reserved.