ASP.NET Core Mvc (.NET 6) CRUD Operations using EntityFrameworkCore

By: Suriyal

ASP.NET Core Mvc (.NET 6) CRUD Operations using EntityFrameworkCore

Introduction

In this asp.net core mvc tutorial we are creating a project to preform the CRUD operations using Microsoft Asp .NET Core 6 and EntityFrameworkCore. We are using Visual studio 2022 and MS SQL server for this tutorial.

Table of Contents

    What we are going to learn….. – Glimpse

    Let’s Start

    Step – 1

    Open Visual Studio and click on Create New Project

    Step – 2

    Select ASP.NET Core Web App (Model-View-Controller) – [C# ] and click next button

    Step – 3

    Enter the project name and click on next button

    Step – 4

    Select .Net 6.0 , authentication type None and click on create button

    Once created, your project will look like following

    Step – 5

    Open Models folder and create a Employee class

    Enter the following code in the employee class

    using System.ComponentModel.DataAnnotations;
    
    namespace EmployeeCRUD.Models
    {
        public class Employee
        {
            [Key]
            public int Id { get; set; }
            [Required]
            [Display(Name ="Employee Name")]
            public string Name { get; set; }
            public string Designation { get; set; }
            [DataType(DataType.MultilineText)]
            public string Address { get; set; }        
            public DateTime? RecordCreatedOn { get; set; }
    
        }
    }
    

    Step – 6

    Install the following packages according to your .NET Core version

     <PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.1" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.1" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.1">

    Step – 7

    Create a subclass ApplicationDbContext of DBContext Class to link the database with data model class

    1. Create one folder and name it Data
    1. Create ApplicaitonDbContext class and enter the following code
    using EmployeeCRUD.Models;
    using Microsoft.EntityFrameworkCore;
    
    namespace EmployeeCRUD.Data
    {
        public class ApplicationDbContext:DbContext
        {
            public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options):base(options)
            {
    
            }
    
            public DbSet<Employee> Employees { get; set; }
        }
    }
    

    In the above code we are passing parameter DbContextOptions<ApplicationDbContext> using constructor, Using this we are passing context configuration from AddDbContext to DbContext

    Step – 8

    Open appsettings.json and configure the connection string

    The following code of appsettings.json file is with sample data. Replace the sample data as per your system or development environment settings.

    {
      "ConnectionStrings": {
        "DefaultConnection": "Server=EnterServerName; Database=EmployeeDatabase; User Id=sa; Password=EnterPassword; Trusted_Connection=True; MultipleActiveResultSets=true"
      },
    
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft.AspNetCore": "Warning"
        }
      },
      "AllowedHosts": "*"
    }
    

    Step – 9

    Open the program.cs file and add the required services

    1. Register ApplicationDbContext subclass as scoped service in application service provider / dependency injection container.
    2. Enter the following lines of code to register the ApplicaitonDbContext
    // add
    builder.Services.AddDbContext<ApplicationDbContext>(
        options => options.UseSqlServer(
            builder.Configuration.GetConnectionString("DefaultConnection")
            ));
    

    Program.cs File

    using EmployeeCRUD.Data;
    using Microsoft.EntityFrameworkCore;
    
    var builder = WebApplication.CreateBuilder(args);
    
    // Add services to the container.
    builder.Services.AddControllersWithViews();
    
    // add
    builder.Services.AddDbContext<ApplicationDbContext>(
        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();
    

    Step – 10

    Run the migration

    1. Open the package manager console

    Type the following command to run the migration

    add-migration 'initial'

    Migration file

    The following is the code of migration file. You can find this file (20220109062010_initial.cs) under Migration folder

    using System;
    using Microsoft.EntityFrameworkCore.Migrations;
    
    #nullable disable
    
    namespace EmployeeCRUD.Migrations
    {
        public partial class initial : Migration
        {
            protected override void Up(MigrationBuilder migrationBuilder)
            {
                migrationBuilder.CreateTable(
                    name: "Employees",
                    columns: table => new
                    {
                        Id = table.Column<int>(type: "int", nullable: false)
                            .Annotation("SqlServer:Identity", "1, 1"),
                        Name = table.Column<string>(type: "nvarchar(max)", nullable: false),
                        Designation = table.Column<string>(type: "nvarchar(max)", nullable: false),
                        Address = table.Column<string>(type: "nvarchar(max)", nullable: false),
                        RecordCreatedOn = table.Column<DateTime>(type: "datetime2", nullable: false)
                    },
                    constraints: table =>
                    {
                        table.PrimaryKey("PK_Employees", x => x.Id);
                    });
            }
    
            protected override void Down(MigrationBuilder migrationBuilder)
            {
                migrationBuilder.DropTable(
                    name: "Employees");
            }
        }
    }
    

    Step – 11

    Run the following update command to update the database as per this migration file

    update-database

    Database view after migration

    Step – 12

    Add Employee Controller

    1. Right click on Employee folder
    2. click on add
    3. click on controller

    4. Select MVC Controller Empty and click on Add button

    5. Enter the Controller name and press add button

    Step – 13

    Paste the following code in your EmployeeControler.cs file

    using EmployeeCRUD.Data;
    using EmployeeCRUD.Models;
    using Microsoft.AspNetCore.Mvc;
    
    namespace EmployeeCRUD.Controllers
    {
        public class EmployeeController : Controller
        {
            private readonly ApplicationDbContext _context;
            public EmployeeController(ApplicationDbContext context)
            {
                _context = context;
            }
            public IActionResult Index()
            {
                IEnumerable<Employee> objCatlist = _context.Employees;
                return View(objCatlist);
            }
    
            public IActionResult Create()
            {
                return View();
            }
    
            [HttpPost]
            [ValidateAntiForgeryToken]
            public IActionResult Create(Employee empobj)
            {
                if (ModelState.IsValid)
                {
                    _context.Employees.Add(empobj);
                    _context.SaveChanges();
                    TempData["ResultOk"] = "Record Added Successfully !";
                    return RedirectToAction("Index");
                }
    
                return View(empobj);
            }
    
            public IActionResult Edit(int? id)
            {
                if (id == null || id == 0)
                {
                    return NotFound();
                }
                var empfromdb = _context.Employees.Find(id);
    
                if (empfromdb == null)
                {
                    return NotFound();
                }
                return View(empfromdb);
            }
    
            [HttpPost]
            [ValidateAntiForgeryToken]
            public IActionResult Edit(Employee empobj)
            {
                if (ModelState.IsValid)
                {
                    _context.Employees.Update(empobj);
                    _context.SaveChanges();
                    TempData["ResultOk"] = "Data Updated Successfully !";
                    return RedirectToAction("Index");
                }
    
                return View(empobj);
            }
    
            public IActionResult Delete(int? id)
            {
                if (id == null || id == 0)
                {
                    return NotFound();
                }
                var empfromdb = _context.Employees.Find(id);
             
                if (empfromdb == null)
                {
                    return NotFound();
                }
                return View(empfromdb);
            }
    
            [HttpPost]
            [ValidateAntiForgeryToken]
            public IActionResult DeleteEmp(int? id)
            {
                var deleterecord = _context.Employees.Find(id);
                if (deleterecord == null)
                {
                    return NotFound();
                }
                _context.Employees.Remove(deleterecord);
                _context.SaveChanges();
                TempData["ResultOk"] = "Data Deleted Successfully !";
                return RedirectToAction("Index");
            }
    
    
        }
    }
    

    Step – 14

    Add view files

    Create one Employee folder under View folder and create the following files

    1. Index.cshtml
    2. Create.cshtml
    3. Edit.cshtml
    4. Delete.cshtml

    Code of Index.cshtml

    @model IEnumerable<Employee>
    
        @{
        ViewData["Title"] = "Index";
    }
    
    @if (TempData["ResultOk"] != null)
    {
        <h1 class="alert-success">@TempData["ResultOk"]</h1>
    }
    
    <div class="container shadow p-5">
    
        <h1 class="text-center mb-3">CRUD Operations Using .NET Core 6 & Microsoft.EntityFrameworkCore </h1>
    
        <div class="col mb-3">
            <a asp-controller="Employee" asp-action="Create" class="btn btn-lg btn-primary"><i class="bi bi-file-plus-fill"></i>Add Employee</a>
        </div>
        <table class="table table-bordered table-hover">
            <thead>
                <tr>
                    <th scope="col">Employee Name</th>
                    <th scope="col">Designation</th>
                    <th scope="col">Address</th>
                    <th scope="col">CreatedOn</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
    
                @foreach (var item in Model)
                {
                    <tr>
                        <td width="20%">
                            @item.Name
                        </td>
                        <td width="20%">
                            @item.Designation
                        </td>
                        <td width="25%">
                            @item.Address
                        </td>
                        <td width="20%">
                            @item.RecordCreatedOn
                        </td>
                        <td>
                            <div role="group" class="w-60 btn-group">
                                <a asp-controller="Employee" asp-action="Edit" asp-route-id="@item.Id" class=" btn btn-sm btn-primary"><i class="bi bi-pencil-square"></i>Edit</a>&nbsp;
                                <a asp-controller="Employee" asp-action="Delete" asp-route-id="@item.Id" class="btn btn-sm btn-danger"><i class="bi bi-trash-fill"></i>Delete</a>
                            </div>
                        </td>
                    </tr>
                }
            </tbody>
        </table>
    </div>
    

    Create.cshtml

    @model Employee
    
    
    <div class="container shadow p-5">
        <div class="row pb-2">
            <h2>Add Employee</h2>
        </div>
    
        <form method="post">
            <div asp-validation-summary="All"></div>
    
            <div class="form-row">
                <div class="form-group col-md-6">
                    <label asp-for="Name">Employee Name</label>
                    <input type="text" class="form-control mb-3" asp-for="Name" placeholder="Enter Name">
                    <span asp-validation-for="Name" class=" alert-danger"></span>
                </div>
                <div class="form-group col-md-6">
                    <label asp-for="Designation">Designation</label>
                    <input type="text" class="form-control mb-3" asp-for="Designation" placeholder="Enter Designation">
                    <span asp-validation-for="Designation" class=" alert-danger"></span>
                </div>
            </div>
    
            <div class="form-row">
                <div class="form-group col-md-6">
                    <label asp-for="Address">Address</label>
                    <input type="text" class="form-control mb-3" asp-for="Address" placeholder="Enter Address">
                    <span asp-validation-for="Address" class=" alert-danger"></span>
                </div>
                <div class="form-group col-md-6 mb-3">
                    <label asp-for="RecordCreatedOn">Created On</label>
                    <input type="datetime-local" class="form-control" asp-for="RecordCreatedOn">
                    <span asp-validation-for="RecordCreatedOn" class=" alert-danger"></span>
                </div>
            </div>
    
    
            <button type="submit" class="btn btn-lg btn-primary p-2"><i class="bi bi-file-plus-fill"></i>Save</button>
            <a asp-controller="Employee" asp-action="Index" class="btn btn-lg btn-warning p-2">Back To List</a>
        </form>
    
    </div>
    
    
    @*//for front end validations*@
    
    @section Scripts{
        @{
        <partial name="_ValidationScriptsPartial" />
        }
    }
    

    Edit.cshtml

    @model Employee
    
    <div class="container shadow p-5">
        <div class="row pb-2">
            <h2>Edit Employee</h2>
        </div>
    
        <form method="post" asp-action="Edit">
            <div asp-validation-summary="All"></div>
    
            <div class="form-row">
                <div class="form-group col-md-6">
                    <label asp-for="Name">Employee Name</label>
                    <input type="text" class="form-control mb-3" asp-for="Name">
                    <span asp-validation-for="Name" class=" alert-danger"></span>
                </div>
                <div class="form-group col-md-6">
                    <label asp-for="Designation">Designation</label>
                    <input type="text" class="form-control mb-3" asp-for="Designation">
                    <span asp-validation-for="Designation" class=" alert-danger"></span>
                </div>
            </div>
    
            <div class="form-row">
                <div class="form-group col-md-6">
                    <label asp-for="Address">Address</label>
                    <input type="text" class="form-control mb-3" asp-for="Address">
                    <span asp-validation-for="Address" class=" alert-danger"></span>
                </div>
                <div class="form-group col-md-6 mb-3">
                    <label asp-for="RecordCreatedOn">Created On</label>
                    <input type="datetime-local" class="form-control" asp-for="RecordCreatedOn">
                    <span asp-validation-for="RecordCreatedOn" class=" alert-danger"></span>
                </div>
            </div>
    
    
            <button type="submit" class="btn btn-lg btn-primary p-2"><i class="bi bi-file-plus-fill"></i>Update</button>
            <a asp-controller="Employee" asp-action="Index" class="btn btn-lg btn-warning p-2">Back To List</a>
        </form>
    
    </div>
    
    
    @*//for front end validations*@
    
    @section Scripts{
        @{
        <partial name="_ValidationScriptsPartial" />
        }
    }
    

    Delete.cshtml

    @model Employee
    
    <div class="container shadow p-5">
        <div class="row pb-2">
            <h2>Delete Employee</h2>
        </div>
    
        <form method="post" asp-action="DeleteEmp">
            <input asp-for="Id" hidden />
            <div asp-validation-summary="All"></div>
    
            <div class="form-row">
                <div class="form-group col-md-6">
                    <label asp-for="Name">Employee Name</label>
                    <input type="text" class="form-control mb-3" asp-for="Name" disabled>
                    <span asp-validation-for="Name" class=" alert-danger"></span>
                </div>
                <div class="form-group col-md-6">
                    <label asp-for="Designation">Designation</label>
                    <input type="text" class="form-control mb-3" asp-for="Designation" disabled>
                    <span asp-validation-for="Designation" class=" alert-danger"></span>
                </div>
            </div>
    
            <div class="form-row">
                <div class="form-group col-md-6">
                    <label asp-for="Address">Address</label>
                    <input type="text" class="form-control mb-3" asp-for="Address" disabled>
                    <span asp-validation-for="Address" class=" alert-danger"></span>
                </div>
                <div class="form-group col-md-6 mb-3">
                    <label asp-for="RecordCreatedOn">Created On</label>
                    <input type="datetime-local" class="form-control" asp-for="RecordCreatedOn" disabled>
                    <span asp-validation-for="RecordCreatedOn" class=" alert-danger"></span>
                </div>
            </div>
             
    
            <button type="submit" class="btn btn-lg btn-danger p-2"><i class="bi bi-trash-fill"></i>Delete</button>
            <a asp-controller="Employee" asp-action="Index" class="btn btn-lg btn-warning p-2">Back To List</a>
        </form>
    
    </div>
    
    
    @*//for front end validations*@
    
    @section Scripts{
        @{
        <partial name="_ValidationScriptsPartial" />
        }
    }
    

    Step – 15

    Finally run the app and test all functionalities !

    Thank you for reading this Asp.net Core 6 CRUD tutorial

    Have a great learning experience !

    15 responses to “ASP.NET Core Mvc (.NET 6) CRUD Operations using EntityFrameworkCore”

    1. Hello,

      This is lovely code and descriptions. Well done Mr. Suryal.
      Please create an application using more than 2-Table.
      Please keep continue.

      I hope All is well
      Abhay, Noida

    2. Hello Mr. Suryal,

      This is lovely code and descriptions. Well done Mr. Suryal.
      Please create an application using more than 2-Table.
      Please keep continue.

      I hope All is well
      Abhay, Noida

    3. Hello Mr. Suryal,

      This is lovely code and descriptions. Well done Mr. Suryal.
      Please create an application using more than 2-Table.
      Please keep continue.

      I hope All is well
      Abhay, Noida

    4. I’m new at this… when I run it I get EmployeeCRUD Home Privacy on my screen. How do I get my CRUD views to display. Are there supposed to be changes to the _Layout code? Project runs OK, Layout has tags for Home and Privacy, but not CRUD views.

    5. Open the program.cs file and change the following line

      pattern: “{controller=Home}/{action=Index}/{id?}”);

      with the following line

      pattern: “{controller=Employee}/{action=Index}/{id?}”);

    6. ALl is best but if master detail concept vidio or like above concept all Data like Images ,Dropdownlist,Datcalander etc Page Create this is the best article For ALL

    7. Hello… Its showing below error
      An unhandled exception occurred while processing the request.
      SqlNullValueException: Data is Null. This method or property cannot be called on Null values.
      Microsoft.Data.SqlClient.SqlBuffer.get_String()

      Stack Query Cookies Headers Routing
      SqlNullValueException: Data is Null. This method or property cannot be called on Null values.
      Microsoft.Data.SqlClient.SqlBuffer.get_String()
      lambda_method11(Closure , QueryContext , DbDataReader , ResultContext , SingleQueryResultCoordinator )
      Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable+Enumerator.MoveNext()
      AspNetCoreGeneratedDocument.Views_TICKET_Management_Index.ExecuteAsync() in Index.cshtml
      +
      @foreach (var item in Model)
      Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context)
      Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, bool invokeViewStarts)
      Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context)
      Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable statusCode)
      Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable statusCode)
      Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ActionContext actionContext, IView view, ViewDataDictionary viewData, ITempDataDictionary tempData, string contentType, Nullable statusCode)
      Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor.ExecuteAsync(ActionContext context, ViewResult result)
      Microsoft.AspNetCore.Mvc.ViewResult.ExecuteResultAsync(ActionContext context)
      Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|30_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
      Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
      Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
      Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
      Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
      Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
      Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
      Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
      Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
      Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
      Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
      Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
      Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

    Leave a Reply

    Your email address will not be published. Required fields are marked *