C
C#4mo ago
daminko

an error occured while sending an update request

This my method :
public async Task<IActionResult> Update([FromRoute] string matricule, [FromBody] UpdateUserRequestDTO updateDto)
{


var user = await _utilisateurService.GetByMatriculeAsync(matricule);
if (user == null)
{
return NotFound();
}

if (user.Data.Role == "Transporteur")
{
var transporteur = await _transporteurService.GetByMatriculeAsync(user.Data);
if (transporteur == null)
{
return NotFound("Transporteur not found");
}

if (transporteur.Data!.VehiculeId != updateDto.VehiculeId)
{
var switchNew = await _vehiculeService.SwitchLibre(updateDto.VehiculeId!);
var switchOld = await _vehiculeService.SwitchLibre(transporteur.Data.VehiculeId!);

if (!switchNew.Success || !switchOld.Success)
{
// Roll back the switch operation if either fails
if (!switchNew.Success)
{
await _vehiculeService.SwitchLibre(transporteur.Data.VehiculeId!);
}
if (!switchOld.Success)
{
await _vehiculeService.SwitchLibre(updateDto.VehiculeId!);
}
return BadRequest("Failed to switch vehicle availability");
}
}

var updatedTransporteur = await _transporteurService.UpdateTransporteur(updateDto, matricule);
return updatedTransporteur.Success ? Ok(updatedTransporteur.Data) : BadRequest(updatedTransporteur.Message);
}

else
{
return BadRequest("Invalid role");
}
}
public async Task<IActionResult> Update([FromRoute] string matricule, [FromBody] UpdateUserRequestDTO updateDto)
{


var user = await _utilisateurService.GetByMatriculeAsync(matricule);
if (user == null)
{
return NotFound();
}

if (user.Data.Role == "Transporteur")
{
var transporteur = await _transporteurService.GetByMatriculeAsync(user.Data);
if (transporteur == null)
{
return NotFound("Transporteur not found");
}

if (transporteur.Data!.VehiculeId != updateDto.VehiculeId)
{
var switchNew = await _vehiculeService.SwitchLibre(updateDto.VehiculeId!);
var switchOld = await _vehiculeService.SwitchLibre(transporteur.Data.VehiculeId!);

if (!switchNew.Success || !switchOld.Success)
{
// Roll back the switch operation if either fails
if (!switchNew.Success)
{
await _vehiculeService.SwitchLibre(transporteur.Data.VehiculeId!);
}
if (!switchOld.Success)
{
await _vehiculeService.SwitchLibre(updateDto.VehiculeId!);
}
return BadRequest("Failed to switch vehicle availability");
}
}

var updatedTransporteur = await _transporteurService.UpdateTransporteur(updateDto, matricule);
return updatedTransporteur.Success ? Ok(updatedTransporteur.Data) : BadRequest(updatedTransporteur.Message);
}

else
{
return BadRequest("Invalid role");
}
}
1 Reply
daminko
daminko4mo ago
then I've got this error back A second operation was started on this context instance before a previous operation completed. This is usually caused by different threads concurrently using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913. I really didn't understand where the threading issue up