ASP.NET CORE - Learn CRUD Operations In Entity Framework Core From Zero To Hero

This CRUD operations tutorial will help beginners learn to build database-driven applications in ASP.NET CORE and Entity Framework Core quickly. Here, the following things are used - ASP.NET CORE, EF CORE, Bootstrap, HTML, CSS, & JavaScript

ASP.NET CORE - Learn CRUD Operations In Entity Framework Core From Zero To Hero

In this ASP.NET Core tutorial, you will learn to perform CRUD operations in Entity Framework Core from the very beginning. This tutorial will help you to learn Entity Framework Core so that you can start using it in your web application.
 

Audience

This tutorial is made for everyone who wants to learn ASP.NET Core and Entity Framework Core quickly. All the things are explained in an easy & step-by-step manner. You can download the complete source code and run them in your PC.

Here, I will perform the CRUD (CREATE, READ, UPDATE & DELETE) operations on a teachers table in the SQL Server database.

This tutorial is divided into the following sections.
  1. Creating a new ASP.NET Core Web Application
  2. Configuring ASP.NET Core Web Application
  3. Create Layout, ViewImports, ViewStart and add Bootstrap
  4. Install EF Core in the Application
  5. Adding Connection String of the Database in the Application
  6. Adding Model class for Teacher
  7. Adding EF Core DbContext File
  8. Creating a Database using EF Core Migration
  9. Adding Controller to the Application
  10. Adding Client-Side Validation feature
  11. Performing the CREATE Teacher Functionality
  12. Performing the READ Teacher Functionality
  13. Performing the UPDATE Teacher Functionality
  14. Performing the DELETE Teacher Functionality 

Creating a new ASP.NET Core Web Application

 
In your Visual Studio, select ‘File > New Project’. A new window will open.

  • On the left side, select ‘Installed > Visual C# > Web’.
  • In the middle part, select ‘ASP.NET Core Web Application’.
  • In the lower part, give your project a name as ‘CRUDEF’ or anything you want, and select the location on the drive where project files will be stored. Also, select the option – ‘Create directory for solution’ and finally click the ‘OK’ button to create your project.

    ASP.NET CORE - Learn CRUD Operations In Entity Framework Core From Zero To Hero
Next, a new window will open to ask you to select the project template, .NET framework, and a few more things. In this window, make sure you select these things.

  • On the 2 drop-downs at the top, select ‘.NET Core’ and ‘ASP.NET Core 2.0. You can also select the ASP.NET Core version greater than 2.0.
  • Select the ‘Empty’ project template.
  • Click the ‘OK’ button to create your ASP.NET Core Web Application
ASP.NET CORE - Learn CRUD Operations In Entity Framework Core From Zero To Hero
 

Configuring ASP.NET Core Web Application

 
Your application should have the support of MVC framework, routing, and Static files. All this can be done from the ‘Startup.cs’ class which is located in the root of the application.

Open the Startup.cs class and add these supports inside the ConfigureServices() and Configure() methods as shown below:

  1. using Microsoft.AspNetCore.Builder;  
  2. using Microsoft.AspNetCore.Hosting;  
  3. using Microsoft.Extensions.DependencyInjection;  
  4.   
  5. namespace CRUDEF  
  6. {  
  7.     public class Startup  
  8.     {  
  9.         public void ConfigureServices(IServiceCollection services)  
  10.         {  
  11.             services.AddMvc();  
  12.         }  
  13.   
  14.         public void Configure(IApplicationBuilder app, IHostingEnvironment env)  
  15.         {  
  16.             app.UseStaticFiles();  
  17.             app.UseDeveloperExceptionPage();  
  18.             app.UseMvc(routes =>  
  19.             {  
  20.                 routes.MapRoute(  
  21.                     name: "default",  
  22.                     template: "{controller=Home}/{action=Index}/{id?}");  
  23.             });  
  24.         }  
  25.     }  
  26. }  
If you want to go into absolute details of ASP.NET Core configuration, then kindly read Configuring Application in ASP.NET Core MVC
 

Create Layout, ViewImports, ViewStart and add Bootstrap

 
Create a ‘Views’ folder in the root of your project, and inside it, create a ‘Shared’ folder.

Next, right-click on the ‘Shared’ folder and select ‘Add > New Item’. You will get a new window showing the item list. From this list, select ‘MVC View Layout Page’ and click the ‘Add’ button.

This will add a _Layout.cshtml file in the Shared folder. The file will be open for editing. You need to add the following code to it.

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <title>@ViewData["Title"]</title>  
  5.     <meta name="viewport" content="width=device-width" />  
  6.     <link href="/lib/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />  
  7. </head>  
  8. <body class="m-1 p-1">  
  9.     @RenderBody()  
  10. </body>  
  11. </html>  
Next, download the Bootstrap Package and extract the Bootstrap zip file contents inside the ‘wwwroot > lib’ folder of your project.

Bootstrap is used to create a responsive layout that is mobile friendly.

Next, right click on the ‘Views’ folder and select ‘Add > New Item’. On the items list, select ‘MVC View Imports Page’ and click the ‘Add’ button. This will add a _ViewImports.cshtml file.

Import the built-in tag helpers & models namespace for the Views, by adding the following code to this file:

  1. @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers  

In the same way, right-click the ‘Views’ folder and select ‘Add > New Item’. On the items list, select the ‘MVC View Start Page’ and click the ‘Add’ button.

This will add the _ViewStart.cshtml file with the following initial code:

  1. @{  
  2.     Layout = "_Layout";  
  3. }  

It tells that all the Views will have the Layout from the _Layout.cshtml file which is located inside the Shared folder.

Install EF Core in the Application

 
EF Core is an Object/Relational Mapping (O/RM) framework, an enhanced version of ADO.NET, which automates data storage and retrieval from the database.

To Install EF Core in your project install the following 3 things provided below,

  1. Install EF Core DB Providers
    Go to Tools > NuGet Package Manager > Package Manager Console and execute the command PM> Install-Package Microsoft.EntityFrameworkCore.SqlServer.

    ASP.NET CORE - Learn CRUD Operations In Entity Framework Core From Zero To Hero

  2. Install EF Core Tools
    Go to Tools > NuGet Package Manager >Manage NuGet Packages for Solution, and search for Microsoft.EntityFrameworkCore.Tools. Once you get the result, install the first one.

    ASP.NET CORE - Learn CRUD Operations In Entity Framework Core From Zero To Hero

  3. Install EF Core Command Line Tools
    The installation of .NET CLI is done in a different manner. Right-click on the project name in the Solution Explorer and select Edit ‘CRUDEF.csproj’.

The project file will open on the Visual Studio. You have to add the below lines to it and save.

  1. <ItemGroup>  
  2.     <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.2" />  
  3. </ItemGroup>  

Adding Connection String of the Database in the Application

 
A Connection String stores the parameters to the database and is used to connect the application to it. These parameters are the name of the driver, Server name and Database name. It also contains security information such as user name and password needed for the database connection.

The connection string is stored inside the appsettings.json file which resides in the root of the application.

Right click on the project name in the Solution Explorer and select Add > New Item. Then when the ‘Add New Item’ window opens up, select ASP.NET Configuration file, and give it the name as appsettings.json (see below image). Finally, click the ‘Add’ button. 
 
ASP.NET CORE - Learn CRUD Operations In Entity Framework Core From Zero To Hero
 
The file will be created and open up for editing in Visual Studio. Add the below connection string to it,
  1. {  
  2.   "ConnectionStrings": {  
  3.     "DefaultConnection""Server=(localdb)\\MSSQLLocalDB;Database=School;Trusted_Connection=True;MultipleActiveResultSets=true"  
  4.   }  
  5. }  

I defined trusted Connection as true in the connection string so the Windows credentials of the current user are used to authenticate against the SQL Server.

Adding Model class for Teacher

 
Right click on the project name in the Solutions Explorer and select ‘Add > New Folder’. Name this folder as ‘Models’. Then right click this ‘Models’ folder and select ‘Add > New Item’.

In the window that opens, select a new Class and name it teachers. Add the following properties to this class:

  1. using CRUDEF.CustomValidation;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.ComponentModel.DataAnnotations;  
  5. using System.Linq;  
  6. using System.Threading.Tasks;  
  7.   
  8. namespace CRUDEF.Models  
  9. {  
  10.     public class Teacher  
  11.     {  
  12.         [Required]  
  13.         public int Id { getset; }  
  14.   
  15.         [Required]  
  16.         public string Name { getset; }  
  17.   
  18.         [Required]  
  19.         [SkillsValidate(Allowed = new string[] { "ASP.NET Core""ASP.NET MVC""ASP.NET Web Forms" }, ErrorMessage = "You skills are invalid")]  
  20.         public string Skills { getset; }  
  21.   
  22.         [Range(5, 50)]  
  23.         public int TotalStudents { getset; }  
  24.   
  25.         [Required]  
  26.         public decimal Salary { getset; }  
  27.   
  28.         [Required]  
  29.         public DateTime AddedOn { getset; }  
  30.     }  
  31. }  

This class has 6 properties for the 6 columns in the Teacher table in the database. I have applied the [Required] attributes on Id, Name, Skills, Salary and AddedOn properties, the TotalStudent property is applied with the [Range] attribute so it will only allow values from 5 to 50.

Also, note the [SkillsValidate] attribute applied to the Skills property. The [SkillsValidate] attribute Is a custom validation attribute through which I will force Skills property to only accept 3 values which are:

  1. ASP.NET Core
  2. ASP.NET MVC
  3. ASP.NET Web Forms

Next, I will create the [SkillsValidate] custom validation attribute. So, create a new folder on the root of the application and name it as ‘CustomValidation’. Inside this folder, add a new class called ‘SkillsValidate.cs’ and add the following code to it.

  1. using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace CRUDEF.CustomValidation  
  8. {  
  9.     public class SkillsValidate : Attribute, IModelValidator  
  10.     {  
  11.         public string[] Allowed { getset; }  
  12.         public string ErrorMessage { getset; }  
  13.         public IEnumerable<ModelValidationResult> Validate(ModelValidationContext context)  
  14.         {  
  15.   
  16.             if (Allowed.Contains(context.Model as string))  
  17.                 return Enumerable.Empty<ModelValidationResult>();  
  18.             else  
  19.                 return new List<ModelValidationResult> {  
  20.                     new ModelValidationResult("", ErrorMessage)  
  21.                 };  
  22.         }  
  23.     }  
  24. }  

Adding EF Core DbContext File

 
You now have to add Entity Framework Core DbContext file for defining your database and tables. So, create a new class called ‘SchoolContext.cs’ and add the following code to it.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using Microsoft.EntityFrameworkCore;  
  6. using Microsoft.Extensions.Configuration;  
  7.   
  8. namespace CRUDEF.Models  
  9. {  
  10.     public class SchoolContext : DbContext  
  11.     {  
  12.         public SchoolContext(DbContextOptions<SchoolContext> options) : base(options) { }  
  13.   
  14.         public DbSet<Teacher> Teacher { getset; }  
  15.   
  16.         protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)  
  17.         {  
  18.             if (!optionsBuilder.IsConfigured)  
  19.             {  
  20.             }  
  21.         }  
  22.   
  23.         protected override void OnModelCreating(ModelBuilder modelBuilder)  
  24.         {  
  25.             modelBuilder.Entity<Teacher>(entity =>  
  26.             {  
  27.                 entity.Property(e => e.Name)  
  28.                     .IsRequired()  
  29.                     .HasMaxLength(50)  
  30.                     .IsUnicode(false);  
  31.   
  32.                 entity.Property(e => e.Skills)  
  33.                     .IsRequired()  
  34.                     .HasMaxLength(250)  
  35.                     .IsUnicode(false);  
  36.   
  37.                 entity.Property(e => e.Salary)  
  38.                     .IsRequired()  
  39.                     .HasColumnType("money");  
  40.   
  41.                 entity.Property(e => e.AddedOn)  
  42.                     .HasColumnType("date")  
  43.                     .HasDefaultValueSql("(getdate())");  
  44.             });  
  45.         }  
  46.     }  
  47. }  

The class inherits from ‘DbContext’ class and defines a ‘DbSet’ of type Teacher. So, when migrations are run, the School database will be created along with the ‘Teacher’ table in it.

Inside the ‘OnModelCreating()’ method I have specified the column types, max length and SQL types for these properties.
 
Now, I have to add SchoolContext class as a service and also specify how it will get the connection string which is stored in the ‘appsettings.json’ file. I do this inside the Startup.cs class, so update its code too.
  1. using CRUDEF.Models;  
  2. using Microsoft.AspNetCore.Builder;  
  3. using Microsoft.AspNetCore.Hosting;  
  4. using Microsoft.EntityFrameworkCore;  
  5. using Microsoft.Extensions.Configuration;  
  6. using Microsoft.Extensions.DependencyInjection;  
  7.   
  8. namespace CRUDEF  
  9. {  
  10.     public class Startup  
  11.     {  
  12.         public Startup(IConfiguration configuration)  
  13.         {  
  14.             Configuration = configuration;  
  15.         }  
  16.   
  17.         public IConfiguration Configuration { get; }  
  18.   
  19.         public void ConfigureServices(IServiceCollection services)  
  20.         {  
  21.             services.AddDbContext<SchoolContext>(options => options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"]));  
  22.             services.AddMvc();  
  23.         }  
  24.   
  25.         public void Configure(IApplicationBuilder app, IHostingEnvironment env)  
  26.         {  
  27.             app.UseStaticFiles();  
  28.             app.UseDeveloperExceptionPage();  
  29.             app.UseMvc(routes =>  
  30.             {  
  31.                 routes.MapRoute(  
  32.                     name: "default",  
  33.                     template: "{controller=Home}/{action=Index}/{id?}");  
  34.             });  
  35.         }  
  36.     }  
  37. }  
See the ‘ConfigureServices()’ method where I have added SchoolContext.cs class as a service and provided with the connection string from the configuration file,
  1. services.AddDbContext<SchoolContext>(options => 
  2.     options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"]));   

Creating a Database using EF Core Migration

 
Now run the Migrations in Entity Framework Core so that the ‘School’ database and ‘Teacher’ table are created. So open the ‘Package Manager Console’ window in Visual Studio then go to the directory of ‘Startup.cs’ class which you can do by running this below command,
  1. PM> cd crudef  

Next, create the migration by the below command,

  1. PM> add-migration SchoolDB  

Finally, create the database and the table by running the update command,

  1. PM> dotnet ef database update  

Now right click the ‘(localdb)\MSSQLLocalDB’ node, in the SQL Server Object Explorer window, and select ‘Refresh’. You will see the School database is created.

ASP.NET CORE - Learn CRUD Operations In Entity Framework Core From Zero To Hero
 
You can find this newly created table called ‘Teachers’ inside the ‘Tables’ node.

The ‘Teacher’ table has 6 columns which are,

  1. Id – a primary key column that will be auto-generated from 1 since it is provided with Identity(1,1) attribute.
  2. Name – a varchar(50) column for storing the name of the teacher.
  3. Skills – for storing the skills of the teacher.
  4. TotalStudents – an Int column for storing the total number of students which a given teacher teaches.
  5. Salary – for storing the salary of the teacher.
  6. AddedOn – for storing the time of the creation of the record. The column has a Date type and is it automatically gets the current time using the GETDATE() SQL function.

Note that all columns have NOT NULL attribute unchecked so they cannot contain NULL in them.

Adding Controller to the Application

 
Create ‘Controllers’ folder on the root of the Application. Inside this folder add a new controller called ‘HomeController.cs’. The controller will have the initial code as shown below:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using Microsoft.AspNetCore.Mvc;  
  6.   
  7. namespace CRUDEF.Controllers  
  8. {  
  9.     public class HomeController : Controller  
  10.     {  
  11.         public IActionResult Index()  
  12.         {  
  13.             return View();  
  14.         }  
  15.     }  
  16. }  

In this controller I will perform the CRUD operation on the ‘Teacher’s’ table. So I will need the ‘StudentContext’ service injected to it using Dependency Injection feature. So update this controller as shown below:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using CRUDEF.Models;  
  6. using Microsoft.AspNetCore.Mvc;  
  7.   
  8. namespace CRUDEF.Controllers  
  9. {  
  10.     public class HomeController : Controller  
  11.     {  
  12.         private SchoolContext schoolContext;  
  13.         public HomeController(SchoolContext sc)  
  14.         {  
  15.             schoolContext = sc;  
  16.         }  
  17.   
  18.         public IActionResult Index()  
  19.         {  
  20.             return View();  
  21.         }  
  22.     }  
  23. }  

Adding Client Side Validation feature

 
The Client Side validation feature is performed by ‘jQuery’ and 2 validation plugins,
  1. jQuery Validation
  2. jQuery Validation Unobtrusive

To install these 3 run the following commands in the ‘Package Manager Console’ window,

  1. 1. PM> Install-Package jQuery -Version 3.3.1  

  2. 2. PM> Install-Package jQuery.Validation -Version 1.17.0  

  3. 3. PM> Install-Package jQuery.Validation.Unobtrusive -Version 2.0.20710  

Performing the CREATE Teacher Functionality

 
The CREATE Teacher Functionality is done through a new Action method called ‘CREATE’. Add this action method to the ‘Home Controller’. It is shown in the below code,
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using CRUDEF.Models;  
  6. using Microsoft.AspNetCore.Mvc;  
  7.   
  8. namespace CRUDEF.Controllers  
  9. {  
  10.     public class HomeController : Controller  
  11.     {  
  12.         private SchoolContext schoolContext;  
  13.         public HomeController(SchoolContext sc)  
  14.         {  
  15.             schoolContext = sc;  
  16.         }  
  17.   
  18.         public IActionResult Index()  
  19.         {  
  20.             return View();  
  21.         }  
  22.   
  23.         public IActionResult Create()  
  24.         {  
  25.             return View();  
  26.         }  
  27.   
  28.         [HttpPost]  
  29.         public IActionResult Create(Teacher teacher)  
  30.         {  
  31.             if (ModelState.IsValid)  
  32.             {  
  33.                 schoolContext.Teacher.Add(teacher);  
  34.                 schoolContext.SaveChanges();  
  35.                 return RedirectToAction("Index");  
  36.             }  
  37.             else  
  38.                 return View();  
  39.         }  
  40.     }  
  41. }  

The [HttpPost] version of the Create action creates a new teacher in the database. It uses Entity Framework Core to create the record. Notice the below 2 lines of code with actually does the insert of the record into the database,

  1. schoolContext.Teacher.Add(teacher);  
  2. schoolContext.SaveChanges();  

Next, add the ‘Views’ folder in the root of the application. Inside this folder create a new folder called ‘Home’.

Next, create a new View called ‘Create.cshtml’ inside this ‘Home’ folder (i.e. ‘Views>Home’). Add the following code to this View,

  1. @model Teacher  
  2.   
  3. @{  
  4.     Layout = "_Layout";  
  5.     var title = "CREATE Teacher";  
  6.     ViewData["Title"] = title;  
  7. }  
  8.   
  9. <style>  
  10.     .input-validation-error {  
  11.         border-color: red;  
  12.     }  
  13. </style>  
  14.   
  15. <h2>@title</h2>  
  16.   
  17. <div asp-validation-summary="ModelOnly" class="text-danger"></div>  
  18. <form class="m-1 p-1" method="post">  
  19.     <div class="form-group">  
  20.         <label asp-for="Name"></label>  
  21.         <input asp-for="Name" class="form-control" />  
  22.         <span asp-validation-for="Name" class="text-danger"></span>  
  23.     </div>  
  24.     <div class="form-group">  
  25.         <label asp-for="Skills"></label>  
  26.         <input asp-for="Skills" type="text" class="form-control" />  
  27.         <span asp-validation-for="Skills" class="text-danger"></span>  
  28.     </div>  
  29.     <div class="form-group">  
  30.         <label asp-for="TotalStudents"></label>  
  31.         <input asp-for="TotalStudents" type="text" class="form-control" />  
  32.         <span asp-validation-for="TotalStudents" class="text-danger"></span>  
  33.     </div>  
  34.     <div class="form-group">  
  35.         <label asp-for="Salary"></label>  
  36.         <input asp-for="Salary" type="text" class="form-control" />  
  37.         <span asp-validation-for="Salary" class="text-danger"></span>  
  38.     </div>  
  39.     <button type="submit" class="btn btn-primary">Submit</button>  
  40. </form>  
  41.   
  42. <script src="/lib/jquery/dist/jquery.min.js"></script>  
  43. <script src="/lib/jquery-validation/dist/jquery.validate.min.js"></script>  
  44. <script src="/lib/jquery-validation-unobtrusive/dist/jquery.validate.unobtrusive.min.js"></script>  

The View has a Model of type ‘Teacher’ and it creates Input fields for ‘Name, Skills, TotalStudents and Salary’, so that user can fill and submit it.

When the Submit button is clicked then the Create Action of type HttpPost, is called and the new teacher records is created.

Notice the 3 script files which do the Client Side Validation of the input fields in the View,

  1. <script src="/lib/jquery/dist/jquery.min.js"></script>  
  2. <script src="/lib/jquery-validation/dist/jquery.validate.min.js"></script>  
  3. <script src="/lib/jquery-validation-unobtrusive/dist/jquery.validate.unobtrusive.min.js"></script>   

Testing the Create Teacher functionality

 
Run the application and in the browser go to the URL of ‘Create’ View, which is – http://localhost:52730/Home/Create. You will see the Create Teacher form in the browser.

Without filling any fields press the Submit button and you will see the validation errors displayed by jQuery Validation plugins.

ASP.NET CORE - Learn CRUD Operations In Entity Framework Core From Zero To Hero
 
Now fill all the fields (as shown by the below image) and click the submit button.
 
ASP.NET CORE - Learn CRUD Operations In Entity Framework Core From Zero To Hero
 
The teacher record will be created in the database and you will be redirected to the Index View which is currently empty.

You can confirm the record is inserted in the Teacher’s table. For this go to the ‘SQL Server Object Explorer’, then right click the ‘Teacher’ table and select ‘View Data’.

The teacher table will open and you will see the new teacher record in it, see the below image:

ASP.NET CORE - Learn CRUD Operations In Entity Framework Core From Zero To Hero 

Performing the READ Teacher Functionality 

 
Now we will create the READ Teacher Functionality. So change the Index Action in the Home Controller to return all the teachers to the View as shown below:
  1. public IActionResult Index()  
  2. {  
  3.     return View(schoolContext.Teacher);  
  4. }  

The code – 'schoolContext.Teacher' will get all the teachers entity from Entity Framework Core.

Next, add the ‘Index’ View inside the ‘Views/Home/’ folder with the following code,

  1. @model IEnumerable<Teacher>  
  2.   
  3. @{  
  4.     Layout = "_Layout";  
  5.     var title = "READ Teacher";  
  6.     ViewData["Title"] = title;  
  7. }  
  8.   
  9. <h2>@title</h2>  
  10.   
  11. <h3><a asp-action="Create" class="btn btn-sm btn-secondary">Create</a></h3>  
  12. <table class="table table-bordered table-sm table-striped">  
  13.     <thead>  
  14.         <tr><th>Id</th><th>Name</th><th>Skills</th><th>Total Students</th><th>Salary</th><th>Added On</th><th>Update</th><th>Delete</th></tr>  
  15.     </thead>  
  16.     <tbody>  
  17.         @if (Model == null)  
  18.         {  
  19.             <tr><td colspan="7" class="text-center">No Model Data</td></tr>  
  20.         }  
  21.         else  
  22.         {  
  23.             @foreach (var p in Model)  
  24.             {  
  25.                 <tr>  
  26.                     <td>@p.Id</td>  
  27.                     <td>@p.Name</td>  
  28.                     <td>@p.Skills</td>  
  29.                     <td>@p.TotalStudents</td>  
  30.                     <td>@string.Format(new System.Globalization.CultureInfo("en-US"), "{0:C2}", p.Salary)</td>  
  31.                     <td>@string.Format("{0:dddd, dd MMMM yyyy}", p.AddedOn)</td>  
  32.                     <td><a asp-action="Update" asp-route-id="@p.Id">Update</a></td>  
  33.                     <td>  
  34.                         <form asp-action="Delete" method="post" asp-route-id="@p.Id">  
  35.                             <button>Delete</button>  
  36.                         </form>  
  37.                     </td>  
  38.                 </tr>  
  39.             }  
  40.         }  
  41.     </tbody>  
  42. </table>  

Notice that I have also created the columns for Update and Delete functionality in the table’s thread and body elements,

  1. <table class="table table-bordered table-sm table-striped">  
  2.     <thead>  
  3.         <tr><th>Id</th><th>Name</th><th>Skills</th><th>Total Students</th><th>Salary</th><th>Added On</th><th>Update</th><th>Delete</th></tr>  
  4.     </thead>  
  5.     <tbody>  
  6.         …  
  7.         else  
  8.         {  
  9.             @foreach (var p in Model)  
  10.             {  
  11.                 <tr>  
  12.                     …  
  13.                     <td><a asp-action="Update" asp-route-id="@p.Id">Update</a></td>  
  14.                     <td>  
  15.                         <form asp-action="Delete" method="post" asp-route-id="@p.Id">  
  16.                             <button>Delete</button>  
  17.                         </form>  
  18.                     </td>  
  19.                 </tr>  
  20.             }  
  21.         }  
  22.     </tbody>  
  23. </table>  

We will create the Update and Delete Functionality in the next sections.

Testing the Read Teacher functionality

 
Run your application and you will see the Teacher’s table records get displayed in the Index View. This is shown by the below image,
 
ASP.NET CORE - Learn CRUD Operations In Entity Framework Core From Zero To Hero 

Performing the UPDATE Teacher functionality

 
Add the 2 Update Actions to the Home Controller as shown below:
  1. public IActionResult Update(int id)  
  2. {  
  3.     return View(schoolContext.Teacher.Where(a => a.Id == id).FirstOrDefault());  
  4. }  
  5.   
  6. [HttpPost]  
  7. [ActionName("Update")]  
  8. public IActionResult Update_Post(Teacher teacher)  
  9. {  
  10.     schoolContext.Teacher.Update(teacher);  
  11.     schoolContext.SaveChanges();  
  12.     return RedirectToAction("Index");  
  13. }  

The HttpGet version of Update action method takes the ‘id’ of the Teacher records in its parameter and fetches the record from the database using EF Core like,

  1. schoolContext.Teacher.Where(a => a.Id == id).FirstOrDefault());  

The HttpPost version of Update action method takes the Teacher class in it’s parameter which is bound with updated values from the Update View. The Updated values are saved in the database table by EF core like this,

  1. schoolContext.Teacher.Update(teacher);  
  2. schoolContext.SaveChanges();  

Next, create the Update View inside the ‘Views/Home/’ folder with the following code,

  1. @model Teacher  
  2.   
  3. @{  
  4.     Layout = "_Layout";  
  5.     var title = "UPDATE Teacher";  
  6.     ViewData["Title"] = title;  
  7. }  
  8.   
  9. <style>  
  10.     .input-validation-error {  
  11.         border-color: red;  
  12.     }  
  13. </style>  
  14.   
  15. <h2>@title</h2>  
  16.   
  17. <div asp-validation-summary="ModelOnly" class="text-danger"></div>  
  18. <form class="m-1 p-1" method="post">  
  19.     <div class="form-group">  
  20.         <label asp-for="Id"></label>  
  21.         <input asp-for="Id" type="text" readonly class="form-control" />  
  22.     </div>  
  23.     <div class="form-group">  
  24.         <label asp-for="Name"></label>  
  25.         <input asp-for="Name" type="text" class="form-control" />  
  26.         <span asp-validation-for="Name" class="text-danger"></span>  
  27.     </div>  
  28.     <div class="form-group">  
  29.         <label asp-for="Skills"></label>  
  30.         <input asp-for="Skills" type="text" class="form-control" />  
  31.         <span asp-validation-for="Skills" class="text-danger"></span>  
  32.     </div>  
  33.     <div class="form-group">  
  34.         <label asp-for="TotalStudents"></label>  
  35.         <input asp-for="TotalStudents" type="text" class="form-control" />  
  36.         <span asp-validation-for="TotalStudents" class="text-danger"></span>  
  37.     </div>  
  38.     <div class="form-group">  
  39.         <label asp-for="Salary"></label>  
  40.         <input asp-for="Salary" type="text" class="form-control"/>  
  41.         <span asp-validation-for="Salary" class="text-danger"></span>  
  42.     </div>  
  43.     <div class="form-group">  
  44.         <label asp-for="AddedOn"></label>  
  45.         <input asp-for="AddedOn" type="text" class="form-control" asp-format="{0:d}" />  
  46.     </div>  
  47.     <button type="submit" class="btn btn-primary">Submit</button>  
  48. </form>  
  49.   
  50. <script src="/lib/jquery/dist/jquery.min.js"></script>  
  51. <script src="/lib/jquery-validation/dist/jquery.validate.min.js"></script>  
  52. <script src="/lib/jquery-validation-unobtrusive/dist/jquery.validate.unobtrusive.min.js"></script>  

The View is similar to the Index View we created earlier. I have made the ‘Id’ field as readonly so that user cannot change it.

Testing the Update Teacher functionality

 
Run your application and click the ‘Update’ link for the 1st teacher records, see below image,
 
ASP.NET CORE - Learn CRUD Operations In Entity Framework Core From Zero To Hero
 
The record will open for updation. Change name to ‘Bill Gates’ and salary to ‘100000000’. Finally click the submit button as shown by the below image,
 
ASP.NET CORE - Learn CRUD Operations In Entity Framework Core From Zero To Hero
 
Record will be updated and you will be redirected to the Index View where you can see the updated record fields as shown by the below image,
 
ASP.NET CORE - Learn CRUD Operations In Entity Framework Core From Zero To Hero 

Performing the DELETE Teacher Functionality

 
Create Delete Action method in the Home Controller whose code is given below:
  1. [HttpPost]  
  2. public IActionResult Delete(int id)  
  3. {  
  4.     var teacher = schoolContext.Teacher.Where(a => a.Id == id).FirstOrDefault();  
  5.     schoolContext.Teacher.Remove(teacher);  
  6.     schoolContext.SaveChanges();  
  7.     return RedirectToAction("Index");  
  8. }  

This method takes the id of the teacher’s record in its parameter and fetches that record from the database table using the below EF Core code:

  1. var teacher = schoolContext.Teacher.Where(a => a.Id == id).FirstOrDefault();  
Finally it deletes that record from the database table like: 
  1. schoolContext.Teacher.Remove(teacher);  
  2. schoolContext.SaveChanges();  

Testing the Delete Teacher functionality

 
Run your application and click the ‘Delete’ link given against any of the record. Check the below images which shows the record deletion process,
 
ASP.NET CORE - Learn CRUD Operations In Entity Framework Core From Zero To Hero
 
ASP.NET CORE - Learn CRUD Operations In Entity Framework Core From Zero To Hero 

Conclusion

 
This completes this CRUD operations tutorial in ASP.NET Core and Entity Framework core. I hope you loved reading this and now understand how the codes are working. If you have any confusion go through all the Source Codes which you can download from this tutorial itself. 
 
I have also written a related tutorial in C# Corner which you should read - 5 Quick Ways To Delete Duplicate Records From Database Which Every Developer Must Know
 
Please like and share this tutorial on your Facebook and Twitter accounts and let your friends learn ASP.NET Core. It hardly takes a few seconds of your time. 
 
Thank you!