将数据保存到数据库一次后,不再保存第二次

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

我对这个行业还很陌生。

这是BaseRepository中的Create方法:

    public async Task CreateAsync(TEntity entity)
    {
        await _db.Set<TEntity>().AddAsync(entity);
        await _db.SaveChangesAsync();
    }

这是 UserService 类中的 Create 方法。

    public  ResultService<UserCreateDTO> Create(UserCreateVM userCreateVM)
    {
        ResultService<UserCreateDTO> result = new ResultService<UserCreateDTO>();

        UserCreateDTO createDto = _mapper.Map<UserCreateDTO>(userCreateVM);
        User newUser = _mapper.Map<User>(createDto);
        var addedUser =  _userRepo.CreateAsync(newUser);

        if (addedUser != null)
        {
            result.Data = createDto;
        }
        else
        {
            result.AddError(ErrorType.BadRequest, "Ekleme işlemi başarısız");
        }
        return result;
    }

这是我们在 API 中的 Post 方法:

    // POST api/<UserController>
    [HttpPost]
    public async Task<ActionResult<UserCreateDTO>> Post([FromBody] UserCreateDTO userDTO, int id)
    {
        if(userDTO == null)
        {
            return BadRequest();
        }

        var user = new User
        {
            ImagePath = userDTO.ImagePath,
            FirstName = userDTO.FirstName,
            LastName = userDTO.LastName,
            SecondLastName = userDTO.SecondLastName,
            BirthDate = userDTO.BirthDate,
            BirthPlace = userDTO.BirthPlace,
            TcNo = userDTO.TcNo,
            DateOfStart = DateTime.Now,
            DateOfExit = userDTO.DateOfExit,
            CompanyName = userDTO.CompanyName,
            JobName = userDTO.JobName,
            Department = userDTO.Department,
            Address = userDTO.Address,
            IsActive = userDTO.IsActive,
            Role = userDTO.Role,
            PhoneNumber=userDTO.PhoneNumber,
            Email = userDTO.Email,
            NormalizedEmail = userDTO.NormalizedEmail.ToUpper(),
            SecurityStamp = Guid.NewGuid().ToString(),
            Password = userDTO.Password,
            UserName=userDTO.Username,
            NormalizedUserName=userDTO.NormalizedUsername.ToUpper(),
        };

        UserCreateVM userCreateVM = new UserCreateVM()
        {
            ImagePath = user.ImagePath,
            FirstName = user.FirstName,
            LastName = user.LastName,
            SecondLastName= user.SecondLastName,
            BirthDate = user.BirthDate,
            BirthPlace = user.BirthPlace,
            TcNo = user.TcNo,
            DateOfStart = DateTime.Now,
            DateOfExit= user.DateOfExit,
            CompanyName = user.CompanyName,
            JobName = user.JobName,
            Department = user.Department,
            Address = user.Address,
            IsActive = user.IsActive,
            Role = user.Role,
            PhoneNumber = userDTO.PhoneNumber,
            Email = user.Email.ToUpper(),
            NormalizedEmail= user.NormalizedEmail,
            SecurityStamp = Guid.NewGuid().ToString(),
            Password = user.Password,
            Username = user.UserName,
            NormalizedUsername=user.NormalizedUserName.ToUpper()
            
        };


        var createdUser =  _userService.Create(userCreateVM);

        if(createdUser != null)
        {
            return CreatedAtAction(nameof(Get), new { id = userDTO.Id }, createdUser);
        }
        return BadRequest();
    }

这些方法的结果是,将用户的数据保存到数据库一次后,并没有执行另一次保存操作,但看起来就像已经保存在Swagger中一样。如果知道原因的人可以写下它,我将不胜感激。我为我的英语有点糟糕而道歉。

我尝试使“UserService”中的“Create”方法异步,但在“var addedUser = _userRepo.CreateAsync(newUser);”行遇到错误。修复错误后,我将该方法恢复到原始状态,因为我在 Swagger 中收到了 500 错误。

c# asp.net api post async-await
1个回答
0
投票

您遇到的问题似乎是由于您处理异步调用和等待

CreateAsync
中的
UserService
函数造成的。因为
CreateAsync
是一个异步函数,所以您应该等待它完成后再继续保证用户被真正添加到数据库中。以下是如何更改
Create
类中的
UserService
函数:

public async Task<ResultService<UserCreateDTO>> CreateAsync(UserCreateVM userCreateVM)
{
    ResultService<UserCreateDTO> result = new ResultService<UserCreateDTO>();

    UserCreateDTO createDto = _mapper.Map<UserCreateDTO>(userCreateVM);
    User newUser = _mapper.Map<User>(createDto);

    // Use await here to ensure the user is added to the database before proceeding
    var addedUser = await _userRepo.CreateAsync(newUser);

    if (addedUser != null)
    {
        result.Data = createDto;
    }
    else
    {
        result.AddError(ErrorType.BadRequest, "Ekleme işlemi başarısız");
    }

    return result;
}

通过在

await
之前包含
_userRepo.CreateAsync(newUser)
,您可以确保用户创建过程是异步且完整的,然后再继续
Create
函数中的下一个阶段。这应该可以解决用户似乎没有保存到数据库的问题。要遵循异步模式,请将
Create
函数的返回类型更改为
TaskResultServiceUserCreateDTO>>
。另外,请记住将对 API 代码中的任何调用
Create
更改为
await _userService.CreateAsync(userCreateVM)
。另外,请确保您的数据库上下文和存储库方法 (
CreateAsync
) 已设置为异步活动。

© www.soinside.com 2019 - 2024. All rights reserved.