Home > OS >  Update method does not update
Update method does not update

Time:08-03

So far the get/delete/create works, but when I'm trying my update method it doesn't work. the weird part is that the api is looping. Any help would be appreciated

how my api looks:

[
  {
    "KlantId": 5,
    "Mailaddres": "ToBeEdited",
    "Wachtwoord": "ToBeEdited",
    "Klantvoornaam": "ToBeEdited",
    "Tussenvoegsel": "ToBeEdited",
    "Klantachternaam": "ToBeEdited",
    "Bedrijfsnaam": "ToBeEdited",
    "Telefoonnummer": "500"
  }
]

Postman request

Postman request

IRepository.cs:

public interface IRepository<T>
{
    Task<List<T>> GetData();
    Task<T> GetDataById(int id);
    Task<T> InsertData(T service);
    Task<T> UpdateData(T service);
    Task<bool> DeleteData(T service);
}

KlantRepository.cs:

public class KlantRepository: IRepository<KlantModel>
{
    private readonly DataContext _context;

    public async Task<KlantModel> UpdateData(KlantModel klant)
    {
        Console.WriteLine("Update method invoked");

        _context.Update(klant).Property(x => x.KlantId).IsModified = false;
        _context.SaveChanges();

        await UpdateData(klant);
        return klant;
    }
}

KlantController.cs:

 [ApiController]
 [Route("api/Klant")]
 [Produces("application/json")]
 public class KlantController : ControllerBase
 {

    private readonly IRepository<KlantModel> _repo;
    private readonly IMapper _mapper;

    public KlantController(IRepository<KlantModel> repo, IMapper mapper)
    {
        _repo = repo;
        _mapper = mapper;
    }

    [HttpPut("{id}")]
    public async Task<ActionResult<KlantModel>> UpdateService( int id, KlantModel klant)
    {
        Console.WriteLine("Update Service Method Invoked");

        Console.WriteLine("KlantId: "   klant.KlantId   " Klant-Bedrijfsnaam: "    klant.Bedrijfsnaam);

        try
        {
            if (klant is null)
            {
                return BadRequest("klant object is null");
            }

            if (!ModelState.IsValid)
            {
                return BadRequest("Invalid model object");
            }

            var klanten = await _repo.GetDataById(id);

            Console.WriteLine("employeeToUpdate-Id: "   klanten.KlantId   " employeeToUpdate-Bedrijfsnaam: "    klanten.Bedrijfsnaam );

            if (klanten is null)
            {
                return NotFound();
            }

            _mapper.Map(klant, klanten);

            await _repo.UpdateData(klanten);

            return NoContent();
        }
        catch (Exception ex)
        {
            return StatusCode(500, $"Internal server error: {ex.Message}");
        }
        
    }

Part 1 is from KlantController.cs

A should be information from Postman

B should be information from the database

Part 2 is Klant repository that he keeps looping enter image description here

CodePudding user response:

It is looping because you are looping :)

enter image description here

  • Related