In this article, we are going to discuss how to perform CRUD operations with Razor Pages in ASP.NET Core 7.0 or 8.0, using the latest version of the .NET Core framework. Let's start by understanding some basics about Razor Pages and their benefits.

In MVC applications, creating a controller, adding action methods, and then adding views is a common approach. However, with Razor Pages, we can simplify this process. Razor Pages resemble traditional ASP.NET web application pages (like .aspx pages), where we can design our views and write code to handle user actions (such as delete, post, get, etc.) on the same page.

In this post, we will demonstrate how to create a PageModel class to fetch all teachers from the database and pass them to a Razor Page for display. Additionally, we will create a user interface to display all teachers from the database and perform CRUD operations on teacher objects. This includes creating a new teacher, editing an existing teacher, deleting a teacher, and viewing all teachers in the database.

Now, let's write code for CRUD operations in ASP.NET Core using Razor Pages. Assume we have a table named Teacher with fields Id, FullName, EmailAddress, DepartmentName, and Salary.

Here's a step-by-step guide to implementing CRUD operations (Create, Read, Update, Delete) using Entity Framework Core for a Teacher entity in an ASP.NET Core Razor Pages application:

So let's create razor page application



Step 1.Install Entity Framework Core Package:

Installed Entity Framework Core package installed. using the following command in your NuGet Package Manager Console:

Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package Microsoft.EntityFramework.Core.Tools 7.0
Use the CLI

dotnet add package Microsoft.EntityFrameworkCore.SqlServer

dotnet Install-Package Microsoft.EntityFramework.Core.Tools
Step 2.Create the Teacher Model: 
Create a Teacher class with properties corresponding to the fields in the database table:
public class Teacher
{
    public int Id { get; set; }
    public string FullName { get; set; }
    public string EmailAddress { get; set; }
    public string DepartmentName { get; set; }
    public decimal Salary { get; set; }
}
Step 3.Create DbContext: 
Create a DbContext class that inherits from DbContext and includes a DbSet property:
I have created a folder named 'Database', and inside that, we have another folder named 'model'.


public class SchoolDbContext : DbContext
{
    public SchoolDbContext(DbContextOptions<SchoolDbContext> options) : base(options)
    {
    }

    public DbSet<Teacher> Teachers { get; set; }
}
Step 4.Configure Connection String:
Add a connection string to your appsettings.json file or any other configuration source
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "ConnectionStrings": {
    "Myconnection": "Data Source=DESKTOP-MFLCOI2;Initial Catalog=SchoolDb;User ID=sa;Password=adk@1234;Encrypt=false;"
  },
  "AllowedHosts": "*"
}
Step 5.Dependency Injection and DbContext Setup: 
In your Program.cs, configure services and the DbContext:
using Microsoft.EntityFrameworkCore;
using RazorDemoApplication.Database;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();

builder.Services.AddDbContext<SchoolDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("Myconnection")));

var app = builder.Build();
// Add services to the container.


// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();

app.Run();
Step 7.Enable Migrations and Apply: 
In Package Manager Console, run the following command to enable migrations: 


Add-Migration InitialCreate 
Apply Migrations: Apply the migrations to your database by running: 

Update-Database
 
Use the CLI to enable migrations and apply them to your database 
dotnet ef migrations add InitialCreate 
dotnet ef database update
Now, we've set up Entity Framework Code First in your Razor Pages application. 
Step 8: Razor Pages Setup

Create Razor Pages for CRUD operations (Create, Read, Update, Delete). For example, Teachers.cshtml for listing teachers and CreateTeacher.cshtml for creating a new teacher.


Add Razor Pages to Pages Directory:
Place these Razor Pages under the Pages directory of ASP.NET Core project.

Display Teachers List:
Use Razor syntax to iterate through the list of teachers retrieved from the database and display them in the Teachers.cshtml Razor Page.

Create Teacher Form:
Create a form in the CreateTeacher.cshtml Razor Page to take information about a new teacher and submit it to the database.

Update Teacher Form:
Create a form in the EditTeacher.cshtml Razor Page to allow users to update the information of an existing teacher.

Delete Confirmation:
In the DeleteTeacher.cshtml Razor Page, and provide a confirmation message or dialog before deleting a teacher.

Teachers.cshtml
@page
@model TeachersModel
@{
    ViewData["Title"] = "Teachers";
}

<h1>Teachers</h1>

<p>
    <a asp-page="./CreateTeacher" class="btn btn-primary">Add Teacher</a>
</p>
<table class="table">
    <thead>
        <tr>
            <th>Id</th>
            <th>Full Name</th>
            <th>Email Address</th>
            <th>Department Name</th>
            <th>Salary</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var teacher in Model.Teachers)
        {
            <tr>
                <td>@teacher.Id</td>
                <td>@teacher.FullName</td>
                <td>@teacher.EmailAddress</td>
                <td>@teacher.DepartmentName</td>
                <td>@teacher.Salary</td>
                <td>
                    <a asp-page="./EditTeacher" asp-route-id="@teacher.Id" class="btn btn-primary">Edit</a>
                    <a asp-page="./DeleteTeacher" asp-route-id="@teacher.Id" class="btn btn-danger">Delete</a>
                </td>
            </tr>
        }
    </tbody>
</table>

Teachers.cshtml.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using RazorDemoApplication.Database.Models;
using RazorDemoApplication.Database;
using Microsoft.EntityFrameworkCore;

namespace RazorDemoApplication.Pages
{
    public class TeachersModel : PageModel
    {
        private readonly SchoolDbContext _context;

        public TeachersModel(SchoolDbContext context)
        {
            _context = context;
        }

        public IList<Teacher> Teachers { get; set; }

        public async Task<IActionResult> OnGetAsync()
        {
            Teachers = await _context.Teachers.ToListAsync();
            return Page();
        }
    }
}
CreateTeacher.cshtml
@page
@model CreateTeacherModel
@{
    ViewData["Title"] = "Create Teacher";
}

<h1>Create Teacher</h1>

<form method="post">
    <div class="form-group">
        <label for="FullName">Full Name:</label>
        <input type="text" class="form-control" id="FullName" name="FullName">
    </div>
    <div class="form-group">
        <label for="EmailAddress">Email Address:</label>
        <input type="text" class="form-control" id="EmailAddress" name="EmailAddress">
    </div>
    <div class="form-group">
        <label for="DepartmentName">Department Name:</label>
        <input type="text" class="form-control" id="DepartmentName" name="DepartmentName">
    </div>
    <div class="form-group">
        <label for="Salary">Salary:</label>
        <input type="text" class="form-control" id="Salary" name="Salary">
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
</form>
CreateTeacher.cshtml.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using RazorDemoApplication.Database.Models;
using RazorDemoApplication.Database;

namespace RazorDemoApplication.Pages
{
    public class CreateTeacherModel : PageModel
    {
        private readonly SchoolDbContext _context;

        public CreateTeacherModel(SchoolDbContext context)
        {
            _context = context;
        }

        [BindProperty]
        public Teacher Teacher { get; set; }

        public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }

            _context.Teachers.Add(Teacher);
            await _context.SaveChangesAsync();

            return RedirectToPage("./Teachers");
        }
    }
}
EditTeacher.cshtml
@page "{id}"
@model EditTeacherModel
@{
    ViewData["Title"] = "Edit Teacher";
}

<h1>Edit Teacher</h1>

<form method="post">
    <input type="hidden" asp-for="Teacher.Id" />
    <div class="form-group">
        <label asp-for="Teacher.FullName"></label>
        <input asp-for="Teacher.FullName" class="form-control" />
    </div>
    <div class="form-group">
        <label asp-for="Teacher.EmailAddress"></label>
        <input asp-for="Teacher.EmailAddress" class="form-control" />
    </div>
    <div class="form-group">
        <label asp-for="Teacher.DepartmentName"></label>
        <input asp-for="Teacher.DepartmentName" class="form-control" />
    </div>
    <div class="form-group">
        <label asp-for="Teacher.Salary"></label>
        <input asp-for="Teacher.Salary" class="form-control" />
    </div>
    <button type="submit" class="btn btn-primary">Update</button>
</form>
EditTeacher.cshtml.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using RazorDemoApplication.Database.Models;
using RazorDemoApplication.Database;

namespace RazorDemoApplication.Pages
{
    public class EditTeacherModel : PageModel
    {
        private readonly SchoolDbContext _context;

        public EditTeacherModel(SchoolDbContext context)
        {
            _context = context;
        }

        [BindProperty]
        public Teacher Teacher { get; set; }

        public async Task<IActionResult> OnGetAsync(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            Teacher = await _context.Teachers.FindAsync(id);

            if (Teacher == null)
            {
                return NotFound();
            }
            return Page();
        }

        public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }

            _context.Attach(Teacher).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!TeacherExists(Teacher.Id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return RedirectToPage("./Teachers");
        }

        private bool TeacherExists(int id)
        {
            return _context.Teachers.Any(e => e.Id == id);
        }
    }
}
DeleteTeacher.cshtml
@page "{id}"
@model DeleteTeacherModel
@{
    ViewData["Title"] = "Delete Teacher";
}

<h1>Delete Teacher</h1>

<p>Are you sure you want to delete teacher: @Model.Teacher.FullName?</p>

<form method="post">
    <input type="hidden" asp-for="Teacher.Id" />
    <button type="submit" class="btn btn-danger">Delete</button>
    <a asp-page="Teachers" class="btn btn-secondary">Cancel</a>
</form>
DeleteTeacher.cshtml.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using RazorDemoApplication.Database.Models;
using RazorDemoApplication.Database;
using Microsoft.EntityFrameworkCore;

namespace RazorDemoApplication.Pages
{
    public class DeleteTeacherModel : PageModel
    {
        private readonly SchoolDbContext _context;

        public DeleteTeacherModel(SchoolDbContext context)
        {
            _context = context;
        }

        [BindProperty]
        public Teacher Teacher { get; set; }

        public async Task<IActionResult> OnGetAsync(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            Teacher = await _context.Teachers.FirstOrDefaultAsync(m => m.Id == id);

            if (Teacher == null)
            {
                return NotFound();
            }
            return Page();
        }

        public async Task<IActionResult> OnPostAsync(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            Teacher = await _context.Teachers.FindAsync(id);

            if (Teacher != null)
            {
                _context.Teachers.Remove(Teacher);
                await _context.SaveChangesAsync();
            }

            return RedirectToPage("./Teachers");
        }
    }
}