skip to Main Content

I’m pretty new to this industry.

This is the Create method in BaseRepository:

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

This is the Create method inside the UserService class.

    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;
    }

This is our Post method in the API:

    // 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();
    }

As a result of these methods, after saving the user’s data to the database once, it does not perform another save operation, but it appears as if it has been saved in Swagger. I would greatly appreciate it if someone who knows the reason could write about it. I apologize for my English being a bit bad.

I tried to make the ‘Create’ method in the ‘UserService’ asynchronous, but I encountered an error on the line ‘var addedUser = _userRepo.CreateAsync(newUser);’. After fixing the error, I reverted the method back to its original state because I was getting a 500 error in Swagger.

2

Answers


  1. Chosen as BEST ANSWER
    I have made the adjustments you mentioned. Thank you for your response, but the line in the provided answer is giving me an error with the message Do you have any idea about the reason for this? Thank you very much strong textonce again.
    
     "var addedUser = await _userRepo.CreateAsync(newUser);"
    

    "CS0815 Cannot assign void to an implicitly-typed variable"in my HRManagementProject.BLL.


  2. It appears that the problem you’re experiencing is due to how you’re handling asynchronous calls and awaiting the CreateAsync function in your UserService. Because CreateAsync is an asynchronous function, you should wait for it to complete before proceeding to guarantee that the user is truly added to the database. Here’s how to change the Create function in the UserService class:

    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;
    }
    

    By including await before _userRepo.CreateAsync(newUser), you ensure that the user creation procedure is asynchronous and complete before proceeding to the next stages in your Create function. This should remedy the issue where the user does not appear to be saved to the database. To follow the asynchronous pattern, change the return type of your Create function to Task<ResultService<UserCreateDTO>>. Also, remember to change any calls to Create in your API code to await _userService.CreateAsync(userCreateVM). Also, make sure your database context and repository methods (CreateAsync) are set up for asynchronous activities.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search