oddvocado
oddvocado

Reputation: 11

Using EF Core to delete item from ToDo list

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.

Upvotes: 0

Views: 456

Answers (1)

Vadim Martynov
Vadim Martynov

Reputation: 8892

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

Upvotes: 1

Related Questions