Start learning free

LESSON 72 OF 173 · BACKEND: APIS WITH A DATABASE

Delete a Product (DELETE) in C#

Practice

The shop stops selling the Gift card. To remove a product, a client sends a DELETE to the product's own path, /products/8: the third method on that path, after GET and PUT. It needs no body: the id in the path says it all.

Here is a DELETE on another table, a list of newsletter subscribers:

var cmd = db.CreateCommand();
cmd.CommandText = "DELETE FROM subscribers WHERE id = $id";
cmd.Parameters.AddWithValue("$id", 3);
Console.WriteLine(cmd.ExecuteNonQuery());   // 1 if subscriber 3 was there, 0 if not

The WHERE matters even more than in an UPDATE: DELETE FROM products alone empties the whole table. Deleting an id that isn't there is no error, it just removes nothing, so ExecuteNonQuery() gives back 0 and you answer 404. When a product is removed, you answer 204 No Content with an empty body: it worked, and there is nothing to send back.

Starting from the shop's 8 products, your code must answer, in this order:

DELETE /products/8  →  204  (empty body)
GET /products/8  →  404  {"error": "Product not found"}
DELETE /products/8  →  404  {"error": "Product not found"}
DELETE /products/99  →  404  {"error": "Product not found"}

Your task: add the route DELETE /products/{id} with app.MapDelete. Delete that product with a $id parameter. Answer 404 if no row was removed, and otherwise an empty body with the status 204.


Assignment
Follow the Coding Tutorial to add the MapDelete route, which removes a product from the database.


Hint
Give $id its value with AddWithValue, as in the MapPut route. For the 204, return Results.StatusCode(204): it sends the status and no body.


STEP 1 OF 7
    Ctrl + Enter to check

    Db Delete in C#

    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free