Skip to main content
Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Resources
    • Cheatsheets
    • Tech Comparisons
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# ASP.NET MVC ASP.NET Web Forms C C# C#, ASP.NET Core, Dapper
      C#, ASP.NET Core, Dapper, Entity Framework DotNet General Web Development HTML, CSS HTML/CSS Java JavaScript JavaScript, HTML, CSS JavaScript, Node.js Node.js
      Python Python 3.11, Pandas, SQL Python 3.11, SQL Python 3.11, SQLAlchemy Python 3.11, SQLAlchemy, SQL Python 3.11, SQLite React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  1. Home
  2. Blog
  3. ASP.NET Core
  4. ASP.NET CORE CRUD Operations With Entity Framework Core In .NET CORE 8.0

ASP.NET CORE CRUD Operations With Entity Framework Core In .NET CORE 8.0

Date- Nov 21,2023 Updated Jan 2026 6591 Free Download Pay & Download
Entity Framework MVC

1. Creating a new ASP.NET Core Web Application

2. Install EF Core in the Application

3. Adding Connection String to the Database

4. Adding Model class for Teacher

5. Adding EF Core DbContext File

6. Creating a Database using EF Core Migration

7. Adding Controller code

8. Adding Client-Side Validation feature

9. Performing the CREATE Teacher Functionality

10. Performing the READ Teacher Functionality

11. Performing the UPDATE Teacher Functionality

12. Performing the DELETE Teacher Functionality

Install EF Core DB Providers
Go to Tools > NuGet Package Manager > Manage NuGet Packages for Solution and search for Microsoft.EntityFrameworkCore.SqlServer. When it shows up, select it and install it to your app

Install EF Core Tools
Next, search for Microsoft.EntityFrameworkCore.Tools. Once you get the result, install it.
 

Adding Connection String to the Database

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. So add the following Connection string to this file.

  "ConnectionStrings": {
    "DefaultConnection": "Server=.;Database=DbEmployee;Trusted_Connection=True;TrustServerCertificate=True;MultipleActiveResultSets=true"
  },
  

Adding Model class for Teacher

Right-click this ‘Models’ folder and select Add > New Item.

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

Teacher. cs

using System.ComponentModel.DataAnnotations;

namespace CrudOperation8.Models
{
    public class Teacher
    {
        [Required]
        public int Id { get; set; }

        [Required]
        public string Name { get; set; }

        [Required]
        public string Skills { get; set; }

        [Range(5, 50)]
        public int TotalStudents { get; set; }

        [Required]
        public decimal Salary { get; set; }

        [Required]
        public DateTime AddedOn { get; set; }
    }
}


Adding EF Core DbContext File

We now have to add Entity Framework Core Database Context file for defining your database and tables. So, create a new class called SchoolContext.cs (on the root of the app) and add the following code to it.

using CrudOperation8.Models;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Reflection.Emit;
namespace CrudOperation8.DBContext
{
public class SchoolContext : DbContext
{
public SchoolContext(DbContextOptions<SchoolContext> options) : base(options) { }
public DbSet<Teacher> Teacher { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Teacher>(entity =>
{
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false);
entity.Property(e => e.Skills)
.IsRequired()
.HasMaxLength(250)
.IsUnicode(false);
entity.Property(e => e.Salary)
.IsRequired()
.HasColumnType("money");
entity.Property(e => e.AddedOn)
.HasColumnType("date")
.HasDefaultValueSql("(getdate())");
});
}
}
}

Now, I have to add the 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 Program.cs class, so update its code to include the following code line after builder.Services.AddControllersWithViews().

using CrudOperation8.DBContext;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddDbContext<SchoolContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/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.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();

I have added SchoolContext as a service and provided with the connection string from the configuration file,

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 run this below command,

PM> add-migration Migration1
PM> Update-Database

Adding Controller code

To the HomeController.cs file we will write the the Entity Framework Core code to perform CRUD operations for the teachers. We will need the ‘StudentContext’ service injected to it using the Dependency Injection feature. So update this controller as shown below:

HomeController.cs

public class HomeController : Controller
	{
		private SchoolContext schoolContext;
		public HomeController(SchoolContext sc)
		{
			schoolContext = sc;
		}

		public IActionResult Index()
		{
			return View();
		}
	}

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

All these come pre-installed in the app. It is still good to know their installation commands which are given below.

PM> Install-Package jQuery

PM> Install-Package jQuery.Validation

PM> Install-Package jQuery.Validation.Unobtrusive

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,

public IActionResult Create()
{
	return View();
}

[HttpPost]
public IActionResult Create(Teacher teacher)
{
	if (ModelState.IsValid)
	{
		schoolContext.Teacher.Add(teacher);
		schoolContext.SaveChanges();
		return RedirectToAction("Index");
	}
	else
		return View();
}
Next, we create the view for this create action method. So to the Views > Home folder in the app, create a new Razor View - Empty file and name it Create.cshtml.  Add the following code to this View file,
@model Teacher
@{
Layout = "_Layout";
var title = "CREATE Teacher";
ViewData["Title"] = title;
}
<style>
.input-validation-error {
border-color: red;
}
</style>
<h2>@title</h2>
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<form class="m-1 p-1" method="post">
<div class="form-group">
<label asp-for="Name"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Skills"></label>
<input asp-for="Skills" type="text" class="form-control" />
<span asp-validation-for="Skills" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="TotalStudents"></label>
<input asp-for="TotalStudents" type="text" class="form-control" />
<span asp-validation-for="TotalStudents" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Salary"></label>
<input asp-for="Salary" type="text" class="form-control" />
<span asp-validation-for="Salary" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
@section scripts {
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/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, We need to add them to the scripts section given on the _Layout.cshtml page. That is why we have used @section scripts {} and then added the 3 scripts to them.

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

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

Next, to the Index.cshtml view given inside the ‘Views/Home/’ folder, add the following code,

 @model IEnumerable<Teacher>

@{
    Layout = "_Layout";
    var title = "READ Teacher";
    ViewData["Title"] = title;
}

<h2>@title</h2>

<h3><a asp-action="Create" class="btn btn-sm btn-secondary">Create</a></h3>
<table class="table table-bordered table-sm table-striped">
    <thead>
        <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>
    </thead>
    <tbody>
        @if (Model == null)
        {
            <tr><td colspan="7" class="text-center">No Model Data</td></tr>
        }
        else
        {
            @foreach (var p in Model)
            {
                <tr>
                    <td>@p.Id</td>
                    <td>@p.Name</td>
                    <td>@p.Skills</td>
                    <td>@p.TotalStudents</td>
                    <td>@string.Format(new System.Globalization.CultureInfo("en-US"), "{0:C2}", p.Salary)</td>
                    <td>@string.Format("{0:dddd, dd MMMM yyyy}", p.AddedOn)</td>
                    <td><a asp-action="Update" asp-route-id="@p.Id">Update</a></td>
                    <td>
                        <form asp-action="Delete" method="post" asp-route-id="@p.Id">
                            <button>Delete</button>
                        </form>
                    </td>
                </tr>
            }
        }
    </tbody>
</table>

Performing the UPDATE Teacher functionality

Add the 2 Update Actions to the Home Controller as shown below:

 public IActionResult Update(int id)
{
    return View(schoolContext.Teacher.Where(a => a.Id == id).FirstOrDefault());
}

[HttpPost]
[ActionName("Update")]
public IActionResult Update_Post(Teacher teacher)
{
    schoolContext.Teacher.Update(teacher);
    schoolContext.SaveChanges();
    return RedirectToAction("Index");
}

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

 @model Teacher

@{
	Layout = "_Layout";
	var title = "UPDATE Teacher";
	ViewData["Title"] = title;
}

<style>
	.input-validation-error {
		border-color: red;
	}
</style>

<h2>@title</h2>

<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<form class="m-1 p-1" method="post">
	<div class="form-group">
		<label asp-for="Id"></label>
		<input asp-for="Id" type="text" readonly class="form-control" />
	</div>
	<div class="form-group">
		<label asp-for="Name"></label>
		<input asp-for="Name" type="text" class="form-control" />
		<span asp-validation-for="Name" class="text-danger"></span>
	</div>
	<div class="form-group">
		<label asp-for="Skills"></label>
		<input asp-for="Skills" type="text" class="form-control" />
		<span asp-validation-for="Skills" class="text-danger"></span>
	</div>
	<div class="form-group">
		<label asp-for="TotalStudents"></label>
		<input asp-for="TotalStudents" type="text" class="form-control" />
		<span asp-validation-for="TotalStudents" class="text-danger"></span>
	</div>
	<div class="form-group">
		<label asp-for="Salary"></label>
		<input asp-for="Salary" type="text" class="form-control" />
		<span asp-validation-for="Salary" class="text-danger"></span>
	</div>
	<div class="form-group">
		<label asp-for="AddedOn"></label>
		<input asp-for="AddedOn" type="text" class="form-control" asp-format="{0:d}" />
	</div>
	<button type="submit" class="btn btn-primary">Submit</button>
</form>

@section scripts {
	<script src="~/lib/jquery/dist/jquery.min.js"></script>
	<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
	<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
}

Performing the DELETE Teacher Functionality

Create Delete Action method in the Home Controller whose code is given below: 

 [HttpPost]
public IActionResult Delete(int id)
{
	var teacher = schoolContext.Teacher.Where(a => a.Id == id).FirstOrDefault();
	schoolContext.Teacher.Remove(teacher);
	schoolContext.SaveChanges();
	return RedirectToAction("Index");
}

Complete code of home controller.

using CrudOperation8.DBContext;
using CrudOperation8.Models;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;

namespace CrudOperation8.Controllers
{

    public class HomeController : Controller
    {
        private SchoolContext schoolContext;
        public HomeController(SchoolContext sc)
        {
            schoolContext = sc;
        }

        public IActionResult Index()
        {
            return View(schoolContext.Teacher);
        }

        public IActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public IActionResult Create(Teacher teacher)
        {
            if (ModelState.IsValid)
            {
                schoolContext.Teacher.Add(teacher);
                schoolContext.SaveChanges();
                return RedirectToAction("Index");
            }
            else
                return View();
        }

        public IActionResult Update(int id)
        {
            return View(schoolContext.Teacher.Where(a => a.Id == id).FirstOrDefault());
        }

        [HttpPost]
        [ActionName("Update")]
        public IActionResult Update_Post(Teacher teacher)
        {
            schoolContext.Teacher.Update(teacher);
            schoolContext.SaveChanges();
            return RedirectToAction("Index");
        }

        [HttpPost]
        public IActionResult Delete(int id)
        {
            var teacher = schoolContext.Teacher.Where(a => a.Id == id).FirstOrDefault();
            schoolContext.Teacher.Remove(teacher);
            schoolContext.SaveChanges();
            return RedirectToAction("Index");
        }
    }
}

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.

ASPNET CORE CRUD Operations With Entity Framework Core In NET CORE 80

Now fill all the fields (as shown by the below image) and click the submit button.


 ASPNET CORE CRUD Operations With Entity Framework Core In NET CORE 80 2


ASPNET CORE CRUD Operations With Entity Framework Core In NET CORE 80 3

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,

ASPNET CORE CRUD Operations With Entity Framework Core In NET CORE 80 4

Performing the UPDATE Teacher functionality

The 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,
ASPNET CORE CRUD Operations With Entity Framework Core In NET CORE 80 5

Testing the Delete Teacher functionality

Run your application and click the Delete button given against each record. Check the below images which shows the record deletion process,
ASPNET CORE CRUD Operations With Entity Framework Core In NET CORE 80 6

S
Shubham Batra
Programming author at Code2Night — sharing tutorials on ASP.NET, C#, and more.
View all posts →

Related Articles

MVC Crud Operation With Entity Framework
Sep 20, 2020
How to run async method inside sync method in asp.net
Jan 28, 2024
Web Api in Asp.net core
Dec 03, 2022
How to export view as pdf in Asp.Net Core
Jul 05, 2022
Previous in ASP.NET Core
How to fix CWE-23 Path Traversal vulnerability (Snyk)
Next in ASP.NET Core
How to get fcm server key
Buy me a pizza

Comments

🔥 Trending This Month

  • 1
    HTTP Error 500.32 Failed to load ASP NET Core runtime 6,938 views
  • 2
    Error-An error occurred while processing your request in .… 11,272 views
  • 3
    Comprehensive Guide to Error Handling in Express.js 235 views
  • 4
    ConfigurationBuilder does not contain a definition for Set… 19,459 views
  • 5
    Mastering JavaScript Error Handling with Try, Catch, and F… 161 views
  • 6
    Mastering Unconditional Statements in C: A Complete Guide … 21,497 views
  • 7
    Unable to connect to any of the specified MySQL hosts 6,232 views

On this page

🎯

Interview Prep

Ace your ASP.NET Core interview with curated Q&As for all levels.

View ASP.NET Core Interview Q&As

More in ASP.NET Core

  • How to Encrypt and Decrypt Password in Asp.Net 26066 views
  • Exception Handling Asp.Net Core 20797 views
  • HTTP Error 500.31 Failed to load ASP NET Core runtime 20288 views
  • How to implement Paypal in Asp.Net Core 19678 views
  • Task Scheduler in Asp.Net core 17578 views
View all ASP.NET Core posts →

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1770
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • ASP.NET
  • Asp.net Core
  • ASP.NET Core, C#
  • ASP.NET MVC
  • ASP.NET Web Forms
  • C
  • C#
  • C#, ASP.NET Core, Dapper
  • C#, ASP.NET Core, Dapper, Entity Framework
  • DotNet
  • General Web Development
  • HTML, CSS
  • HTML/CSS
  • Java
  • JavaScript
  • JavaScript, HTML, CSS
  • JavaScript, Node.js
  • Node.js
  • Python
  • Python 3.11, Pandas, SQL
  • Python 3.11, SQL
  • Python 3.11, SQLAlchemy
  • Python 3.11, SQLAlchemy, SQL
  • Python 3.11, SQLite
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ·  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor