(C# ASP.NET Core) Deleting Records from a Database with EF Core

We start by explaining the general scheme for deleting a record from a table. A foreach loop adds an anchor link to each record. The primary key (id) of each record is set as an attribute of each respective anchor link, and each anchor link also binds to a handler function in the backing class. When such a link is clicked the handler receives that id as a parameter and a C# code carries on the deletion.

Categories | About |     |  

Parveen,

Quick outline of the EF Core steps

Step 1: Get the item by using its primary key id.

// query the DbSet for the item to delete 
var prod = await _ctx.Products.FindAsync(id);

Step 2: Mark the item for removal.

// mark for removal from DbSet 
_ctx.Products.Remove(prod);

Step 3: Save changes to cause the deletion

// cause the deletion 
await _ctx.SaveChangesAsync();

Video Explanation with a Working Example

Please watch the following youtube video:

How to add anchor link buttons for delete

Tag helpers are used to connect an anchor link button to a function in the backing class, and also to specify any parameters for that function.

The following code uses the attribute asp-page-handler to connect the click event to a function called "Delete" in the backing class, and asp-route-id to specify the parameter id. Nothing else needs to be done - no javascript, nothing else needs to be done - everything is handled by asp.net core.


// route-id is used to pass the primary key id 
// page-handler is used to specify the name of the function 
// that will cause deletion in the backing class 

<a asp-route-id="@prod.ID" asp-page-handler="Delete">Delete</a>

// NOTE: these links are added in a foreach 
// loop as explained in the example next 

Pre-requisites for this Tutorial

You should already have completed the tutorial on display of data - (C# ASP.NET Core) Displaying Data and OnGetAsync

Step 1 of 2: Index.cshtml Razor Page
(see the linked video for details)

Following is the completed file


@page "{handler?}/{id?}"

@model Modular.Pages.IndexModel

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

<h1>Display of Data</h1>

@foreach (var prod in Model.Products)
{
  <div>
    @prod.Name 
    |
    <a asp-route-id="@prod.ID" asp-page-handler="Delete">Delete</a>
  </div>

  <hr />
}

Step 2 of 2: Index.cshtml.cs backing class file
(see the linked video for details)

Following is the code for the backing class. Notice the handler Delete is prefixed as OnGetDelete

using DBaseCon;

using Microsoft.AspNetCore.Mvc;

using Microsoft.AspNetCore.Mvc.RazorPages;

using Microsoft.EntityFrameworkCore;

using System.Collections.Generic;

using System.Threading.Tasks;

namespace Modular.Pages
{

  public class IndexModel : PageModel
  {

    private readonly ProductContext _ctx;

    // dependency injection of the ProductContext 
    public IndexModel(ProductContext ctx)
    {

      _ctx = ctx;

    }

    // using System.Collections.Generic 
    // for Display 
    public IList<Product> Products { get; set; }

    // get the records when the page loads 
    public async void OnGetAsync()
    {

      // using Microsoft.EntityFrameworkCore; 

      Products = await _ctx.Products.ToListAsync();

    }

    // Delete the record Sql DELETE 
    public async Task<IActionResult> OnGetDelete(int? id)
    {

      if (null == id)
      {

        // sends 404 error 
        return NotFound();

      }

      // query the DbSet for the item to delete 
      var prod = await _ctx.Products.FindAsync(id);

      // mark from removal from DbSet 
      _ctx.Products.Remove(prod);

      // cause the deletion 
      await _ctx.SaveChangesAsync();

      return RedirectToPage();

    }

  }

}


This Blog Post/Article "(C# ASP.NET Core) Deleting Records from a Database with EF Core" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.