My previous post demonstrated website development in ASP.NET CORE using the razor page where we learned the basics of building an ASP.NET Core Razor Pages web app.
Here in this post, we will learn the website development using ASP.NET Razor page with CRUD Operations using Entity Framework core and SQL.
CRUD Operations on ASP.NET Razor Page
Getting Started
CRUD operations in ASP.NET Razor Pages involve creating, reading, updating, and deleting data. Razor Pages is a page-based programming model that makes building web UI easier and more productive.
Here we continue the web app development project that we had created while demonstrating in my previous post , to perform create, update, and delete operations (CRUD operations) on razor page using entity framework core and SQL.
I will request you to visit my previous blog post before continuing this post. There you will get understating of how to develop web app development project.
Demonstration of CRUD Operations
In this demonstration, the entity framework database first approach will followed as we already have a database in SQL server to perform CRUD operations on student's entity.
This demonstration includes the following.
- Add a Razor Page Model
- Set up Entity Framework
- Setup Database Context
- Configure Database Connection
- Create Razor Pages
Add a Model
A model class here will be used to store and manage student data. The data of data base (student information) will be displayed on page and managed using this model class. The following steps describe how to add model class in ASP.NET Core.
- In Solution Explorer, right-click the RazorWeb project > Add > New Folder. Name the folder Models.
- Right-click the Models folder. Select Add > Class. Name the class Student.
- Update the student class with below code:
public class Student { public int Id { get; set; } public string StudentName { get; set; } public string Class { get; set; } public string RollNumber { get; set; } }
Setup Entity Framework
To access SQL databases here in the demonstrator, we will use the entity framework core. Download the latest version of below two libraries from NuGet using the NueGet Package manager.
- Microsoft.EntityFrameworkCore
- Microsoft.EntityFrameworkCore.SqlSer
Set Up the Database Context
Add a new folder to you project and name it to DB. Create a new class with name DatabaseContext and update it with below class code, make sure there is no error after coping.
public class DatabaseContext : DbContext
{
public DatabaseContext(DbContextOptions<DatabaseContext> options)
: base(options)
{
}
public DbSet<Student> Students { get; set; }
}
Configure Database Connection
Update the appsettings.json file with database connection string as like below to connect SQL database.
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"ConnectionStrings": {
"BloggingDatabase": "Data Source=NQMUMLAP0151;Initial Catalog=testing;User ID=testuser;Password=testpassword;MultipleActiveResultSets=true;TrustServerCertificate=True;"
},
"policies": {
"Certificates": {
"ImportEnterpriseRoots": true
},
"AllowedHosts": "*"
}
}
Update the program.cs file to use Entity Framework Core with your context as like below.
using Microsoft.EntityFrameworkCore;
using RazorWeb;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddDbContext<DatabaseContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("BloggingDatabase"));
});
var app = builder.Build();
// 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();
Create Razor Pages
This section will produces pages for Create, Read, Update, and Delete (CRUD) operations for the student model by scaffolding the student model class.
-
Create the Pages/Movies folder:
- Right-click on the Pages folder > Add > New Folder.
- Name the folder Students.
- Right-click on the Pages/Students folder > Add > New Scaffolded Item.
- In the Add New Scaffold dialog, select Razor Pages using Entity Framework (CRUD) > Add.
- Complete the Add Razor Pages using Entity Framework (CRUD) dialog:
- In the Model class drop down, select Movie (RazorWeb.Models).
- In the Data context class row, select RazorWeb database context if not automatically selected.
- Click on Add button.
- The page creation process will start, and you will notice below five cshtml files will be created in the students folder with their Page model classes after the process completed.
- Create
- Delete
- Details
- Edit
- Index
Run the project, make sure there is no error. if the project successfully run then follow steps below for creatin a menu in home page to access the index page of Student entity to perform CRUD operations
- In the Solution Explorer, Find the Shared folder and expand it.
- Double click on the _Layout.cshtml file to open it.
- Fine the UL element, the UL element looks like below
<ul class="navbar-nav flex-grow-1">
- Add the below LI element at end of the UL element.
<li class="nav-item"> <a class="nav-link text-dark" asp-area="" asp-page="/Students/Index">Students</a> </li>
Perform Crud
Finally build and run the project. the home page will be appear in the browser. Click on the Students menu resides near the Privacy menu.
Browser will redirect to the Index page of Student, perform the CRUD operation
Thanks
Very nice
ReplyDelete