
This blog is related to a crud operation. In this blog, I show how to add, edit, delete, and get data from a database. I used Visual Studio 2022 and SQL Server 2019 for this crud operation. GitHub URL
Step 1. Create a .net core MVC project version 7 as well as an SQL Server database.

Create Project .NET core MVC (version 7.0)

Create a database in SQL Server
Step 2. Put the default connection string in appsettings.js.
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultString": "Server=***sqlservername***;database=EfCore;Trusted_connection=true"
}
}
Step 3. Add database connection server setup integration in startup.cs class.
using EFCore.Data;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddDbContext<EFCoreDBContext>(service =>
service.UseSqlServer(builder.Configuration.GetConnectionString("DefaultString")));
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Student}/{action=Students}/{id?}");
app.Run();
Step 4. Create two classes The first is a student, and the second is a pager (for pegging).
public class Pager
{
public int TotalItems { get; set; }
public int CurrentPage { get; set; }
public int PageSize { get; set; }
public int TotalPages { get; set; }
public int StartPage { get; set; }
public int EndPage { get; set; }
public Pager()
{
}
public Pager(int totalItems, int page, int pageSize = 10)
{
int totalPages = (int)Math.Ceiling((decimal)totalItems / (decimal)pageSize);
int currentPage = page;
int startpage = currentPage - 5;
int endpage = currentPage + 5;
if (startpage <= 0)
{
endpage = endpage - (startpage - 1);
startpage = 1;
}
if (endpage > totalPages)
{
endpage = totalPages;
if (endpage > 10)
{
startpage = endpage - 9;
}
}
TotalItems = totalItems;
CurrentPage = currentPage;
PageSize = pageSize;
TotalPages = totalPages;
StartPage = startpage;
EndPage = endpage;
}
}
namespace EFCore.Models
{
public class Student
{
public int Id { get; set; }
public int RollNumber { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Class { get; set; }
public DateTime BirthDate { get; set; }
}
}
Step 5. Create a data folder in this application and add one more file named EFCoreDBContext.cs.
Add Nuget package for connection to the database
- Microsoft.EntityFrameworkCore.SqlServer (7.0.0)
- Microsoft.EntityFrameworkCore.Tools(7.0.0)
- Microsoft.VisualStudio.Web.CodeGeneration.Design (7.0.0)
Create a student table in the SQL Server database. Following that, you can navigate to Tools. Nuget Package Manager => Write the following command in the Package Manager Console to connect to the database.
- Add-Migration “initial Migration”
- Update-Database
public class EFCoreDBContext : DbContext
{
public EFCoreDBContext(DbContextOptions options) : base(options)
{
}
// Write these commands:
// Add-Migration "initial Migration"
// Update-Database
public DbSet<Student> Students { get; set; }
}
Step 6. Insert the following code into the Student Controller. cs file.
public class StudentController : Controller
{
public readonly EFCoreDBContext dBContext;
public StudentController(EFCoreDBContext _dBContext)
{
this.dBContext = _dBContext;
}
[HttpGet]
public async Task<IActionResult> Students(string search, int page = 1, int pageSize = 10)
{
search = search ?? "";
try
{
var students = await dBContext.Students
.Where(t => t.Name.Contains(search) || t.Email.Contains(search) || t.Class.Contains(search))
.ToListAsync();
if (page < 1)
{
page = 1;
}
int recsCount = students.Count;
var pager = new Pager(recsCount, page, pageSize);
var recSkip = (page - 1) * pageSize;
students = students.Skip(recSkip).Take(pager.PageSize).ToList();
ViewBag.Pager = pager;
ViewBag.Search = search;
return View(students);
}
catch (Exception)
{
throw;
}
}
[HttpGet]
public async Task<IActionResult> StudentGrid(string search = "", int page = 1, int pageSize = 10)
{
search = search ?? "";
try
{
var students = await dBContext.Students
.Where(t => t.Name.Contains(search) || t.Email.Contains(search) || t.Class.Contains(search))
.ToListAsync();
if (page < 1)
{
page = 1;
}
int recsCount = students.Count;
var pager = new Pager(recsCount, page, pageSize);
var recSkip = (page - 1) * pageSize;
students = students.Skip(recSkip).Take(pager.PageSize).ToList();
ViewBag.Pager = pager;
ViewBag.Search = search;
return PartialView("StudentGrid", students);
}
catch (Exception)
{
throw;
}
}
[HttpGet]
public IActionResult AddStudent()
{
return View();
}
[HttpPost]
public async Task<IActionResult> AddStudent(Student student)
{
if (student.Id == 0)
{
await dBContext.AddAsync(student);
}
else
{
var dstudent = await dBContext.Students.FindAsync(student.Id);
if (dstudent != null)
{
dstudent.RollNumber = student.RollNumber;
dstudent.Name = student.Name;
dstudent.Email = student.Email;
dstudent.Class = student.Class;
dstudent.BirthDate = student.BirthDate;
}
}
await dBContext.SaveChangesAsync();
return RedirectToAction("Students");
}
[HttpGet]
public async Task<IActionResult> EditStudent(int id)
{
var student = await dBContext.Students.FirstOrDefaultAsync(x => x.Id == id) ?? new Student();
return View("AddStudent", student);
}
[HttpGet]
public async Task<IActionResult> DeleteStudent(int id)
{
var student = await dBContext.Students.FindAsync(id) ?? new Student();
if (student != null)
{
dBContext.Students.Remove(student);
await dBContext.SaveChangesAsync();
}
return RedirectToAction("Students");
}
}
Join the conversation! Your thoughts help the community grow.