Asp.net core Crud Operation

Updated : May 22, 2020 in Asp.net core

Crud operation in asp.net core using entity framework core code first

In this article, we will learn about how to implement Crud operation in asp.net core using entity framework core code first using the SQL Server database with the help of the Employee Details Example.

Prerequisites for complete this example:

  • Install asp.net core 2.2 version SDK or above new versions link
  • Install Visual Studio 2019 link
  • Install SQL server Link
  • References for complete this example Link

Once you will finish the above steps we need to know what is asp.net core 2.2? And how to pass data from controller to view? This will help for better understating for this example

Steps for implementing the crud operation in asp.net core?

  • Create  a Database in SQL server or Enable data migration
  • Create an Asp.net core project
  • Establish the database connection
  • Add Employee Model Class
  • Add Employee database Context
  • Add Employee Controller.cs class
  • Implementing the views for ListView,Inset, Edit, Delete

Step 1: Crate a Data base in SQL server

Open SQL server IDE(Integrated Development Environment)  Create a Database  Using given below Query

Create database sampleDB

Select your database SampleDB and execute the given below Query

 USE [SampleDB]
GO

/****** Object:  Table [dbo].[Employee]    Script Date: 21/05/2020 15:14:35 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Employee](
	[EmployeeId] [int] IDENTITY(1,1) NOT NULL,
	[FullName] [nvarchar](50) NOT NULL,
	[EmpCode] [nvarchar](50) NULL,
	[Position] [nvarchar](50) NULL,
	[OfficeLocation] [nvarchar](50) NULL,
	[testcoloumn] [nvarchar](50) NULL,
	[secondtest] [nvarchar](50) NULL,
 CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED 
(
	[EmployeeId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

Add some Employee details

select data base employee

We have two options for creating databases for implementing crud operation in asp.net core

  1. Manually we will create DataBase as like following above steps
  2.  Enable Migration (Code first Approach with Ef)

How to Enable the Migration in asp.net core?

This step you will implement after adding the model class and establish the database connection to with you SQL server.

Migrations are enabled by default in EF Core but you have to install the Microsoft.EntityFrameworkCore.Tools .nuget package. It looks like that package isn’t installed by default with EF Core

How to Enable the Migration in asp.net core for crud operation?

Once Installation is done then after you add following the given command

How to Enable the Migration in asp.net core?
How to Enable the Migration in asp.net core?

Just add new migration with “Add-Migration” command line and enter migration name.

After successfully added the migration it will create a Migration folder in your project

How to Enable the Migration in asp.net core?

Go to your SQL Server Database check in your database you have migration history

For more details about Enable migration you will click

https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/migrations

Step 2: Create an Asp.net core project

Create an ASP.NET Core MVC Project: open Visual Studio, create a new ASP.NET Core  project

set up asp.net core project

Select Empty Template and Click Ok button to Finish

set up asp.net core project

Add Configurations in Startup.cs: Open Startup.cs file in your project and add new configurations as given below code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Asp.netCoreMVCCRUD.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Asp.netCoreMVCCRUD
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddDbContext<EmployeeContext>(options => 
            options.UseSqlServer(Configuration.GetConnectionString("DevConnection")));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Employee}/{action=Index}/{id?}");
            });
        }
    }
}

Step 3: Establish the database connection

Open your appsettings.json file Add your connection string

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DevConnection": "Data Source=..AY\\SQLEXPRESS;Initial Catalog=SampleDB;User ID=sa;Password=**;"
  }
}

step 4: Add Employee Model Class

Create a model folder in your project and add inside the model folder Add Employee.cs file

Employee
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace Asp.netCoreMVCCRUD.Models
{
    public class Employee
    {
        [Key]
        public int EmployeeId { get; set; }
        [Column(TypeName = "nvarchar(250)")]
        [Required(ErrorMessage = "This field is required.")]
        [DisplayName("Full Name")]
        public string FullName { get; set; }
        [Column(TypeName = "varchar(10)")]
        [DisplayName("Emp. Code")]
        public string EmpCode { get; set; }
        [Column(TypeName = "varchar(100)")]
        public string Position { get; set; }
        [Column(TypeName = "varchar(100)")]
        [DisplayName("Office Location")]
        public string OfficeLocation { get; set; }
        public string testcoloumn { get; set; }
        //public string secondtest { get; set; }
    }
}

Step 5 : Add Employee database Context

Add inside model folder EmployeeContext.cs and ErrorViewModel.cs

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Asp.netCoreMVCCRUD.Models
{
    public class EmployeeContext:DbContext
    {
        public EmployeeContext(DbContextOptions<EmployeeContext> options):base(options)
        {
        }
        public DbSet<Employee> Employees { get; set; }
    }
}
using System;

namespace Asp.netCoreMVCCRUD.Models
{
    public class ErrorViewModel
    {
        public string RequestId { get; set; }

        public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
    }
}

Step 6: Add Employee Controller.cs class

Add Controller: Create a new folder named Controllers in your project. In this folder, create a new controller named EmployeeController.cs as given below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Asp.netCoreMVCCRUD.Models;

namespace Asp.netCoreMVCCRUD.Controllers
{
    public class EmployeeController : Controller
    {
        private readonly EmployeeContext _context;

        public EmployeeController(EmployeeContext context)
        {
            _context = context;
        }

        // GET: Employee
        public async Task<IActionResult> Index()
        {
            var daat = await _context.Employees.ToListAsync();
            return View(daat);
        }


        // GET: Employee/Create
        public IActionResult AddOrEdit(int id = 0)
        {
            if (id == 0)
                return View(new Employee());
            else
                return View(_context.Employees.Find(id));
        }

        // POST: Employee/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> AddOrEdit([Bind("EmployeeId,FullName,EmpCode,Position,OfficeLocation")] Employee employee)
        {
            if (ModelState.IsValid)
            {
                if (employee.EmployeeId == 0)
                    _context.Add(employee);
                else
                    _context.Update(employee);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(employee);
        }
        // GET: Employee/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            var employee =await _context.Employees.FindAsync(id);
            _context.Employees.Remove(employee);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
    }
}

Step 7:Implementing the views for ListView,Inset, Edit, Delete

inside the view folder you will add following given views

AddOrEdit.cshtml

@model Asp.netCoreMVCCRUD.Models.Employee

@{
    ViewData["Title"] = "Create";
}

<h4>Employee Form</h4>
<hr />
<div class="row">
    <div class="col-md-6">
        <form asp-action="AddOrEdit">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <input type="hidden" asp-for="EmployeeId" />
            <div class="form-group">
                <label asp-for="FullName" class="control-label"></label>
                <input asp-for="FullName" class="form-control" />
                <span asp-validation-for="FullName" class="text-danger"></span>
            </div>
            <div class="form-row">
                <div class="form-group col-md-6">
                    <label asp-for="EmpCode" class="control-label"></label>
                    <input asp-for="EmpCode" class="form-control" />
                    <span asp-validation-for="EmpCode" class="text-danger"></span>
                </div>
                <div class="form-group col-md-6">
                    <label asp-for="Position" class="control-label"></label>
                    <input asp-for="Position" class="form-control" />
                    <span asp-validation-for="Position" class="text-danger"></span>
                </div>
            </div>
            <div class="form-group">
                <label asp-for="OfficeLocation" class="control-label"></label>
                <input asp-for="OfficeLocation" class="form-control" />
                <span asp-validation-for="OfficeLocation" class="text-danger"></span>
            </div>
            <div class="form-row">
                <div class="form-group col-md-6">
                    <input type="submit" value="Submit" class="btn btn-primary btn-block" />
                </div>
                <div  class="form-group col-md-6">
                    <a asp-action="Index"  class="btn btn-secondary btn-block"><i class="fa fa-table"></i> Back to List</a>
                </div>
            </div>
        </form>
    </div>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

Index.cshtml

@model IEnumerable<Asp.netCoreMVCCRUD.Models.Employee>

@{
    ViewData["Title"] = "Index";
}

<h4>Employee Register</h4>
<hr />


<table class="table table-hover">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.FullName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.EmpCode)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Position)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.OfficeLocation)
            </th>
            <th>
                <a asp-action="AddOrEdit" class="btn btn-outline-success"><i class="far fa-plus-square"></i> Employee</a>
            </th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.FullName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.EmpCode)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Position)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.OfficeLocation)
            </td>
            <td>
                <a asp-action="AddOrEdit" asp-route-id="@item.EmployeeId"><i class="fa fa-marker fa-lg"></i></a>
                <a asp-action="Delete" asp-route-id="@item.EmployeeId" class="text-danger ml-1" onclick="return confirm('Are you sure to delete this record?')"><i class="fa fa-trash-alt fa-lg"></i></a>
            </td>
        </tr>
}
    </tbody>
</table>

See the given below image your project structure

project structure Asp.net core

Add Razor View Imports page: Select Razor View page and click Add button to Finish and Add Inside  _ViewImports.cshtml file and TagHelpers library as given below:

Add Razor View Imports page for asp.net core crud operation
@using Asp.netCoreMVCCRUD
@using Asp.netCoreMVCCRUD.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

Run Project:

Asp.net core Crud Operation
Asp.net core Crud Operation

SandeepMVN
Like
Like Love Haha Wow Sad Angry
38711

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x