0

I was asked to update the API and implement the RemoveToDoItem from the following code:

[HttpDelete("{id}", Name = "DeleteTodoItem")]
public async Task<IActionResult> RemoveTodoItem(int id)
{
    // TODO
    // Use EF Core to remove the item based on id

    throw new NotImplementedException();
}

This is the error code I get when I attempt to run the program

HttpRequestException: you must first implement the API endpoint. Candidate.Web.Services.CandidateApi.RemoveTodoItem(int id) in CandidateApi.cs

        }
        catch (Exception ex)
        {
            throw new HttpRequestException("You must first implement the API endpoint.");
        }

        throw new HttpRequestException("You must first implement the API endpoint.");

Not entirely sure how to go about this. I've tried to use the DeleteTodoItem variable but no luck.

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
oddvocado
  • 13
  • 3
  • Hi and welcome to SO. We’re happy to help you, but in order to improve your chances of getting an answer, here are some guidelines to follow: https://stackoverflow.com/help/how-to-ask – Vadim Martynov Feb 27 '23 at 21:40

1 Answers1

1
  1. Inject your DbContext into the controller by adding it to the constructor parameters.
  2. Use the Remove() method on the DbSet<T> property of your DbContext to mark the entity for deletion.
  3. Call SaveChangesAsync() to persist the changes to the database.
[HttpDelete("{id}", Name = "DeleteTodoItem")]
public async Task<IActionResult> RemoveTodoItem(int id)
{
    var todoItem = await _dbContext.TodoItems.FindAsync(id);

    if (todoItem == null)
        return NotFound();

    _dbContext.TodoItems.Remove(todoItem);
    await _dbContext.SaveChangesAsync();

    return NoContent();
}
Vadim Martynov
  • 8,602
  • 5
  • 31
  • 43
  • Thank you! This helpful. Another question. How would I inject DbContext into the controller by adding it to the constructor parameters? Would I need to create a new class titled under the Models folder? So far I have something like this: public class AppDbContext :DbContext { } } – oddvocado Feb 27 '23 at 22:23
  • https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection – Vadim Martynov Feb 27 '23 at 22:31
  • I've created a models folder for _dbContext. That looks like this { public static object Todos { get; set; } public static object Async { get; set; } public static object TodoItems { get; set; } } Now the only error code that shows up is for FindAsync ('object does not contain definition and no accessible extension method) and .SaveChanges Async (does not contain definition). Feels like I'm close? – oddvocado Feb 28 '23 at 18:32