articles

Home / DeveloperSection / Articles / crud operations in asp .net core with entity framework

crud operations in asp .net core with entity framework

crud operations in asp .net core with entity framework

Anonymous User 1816 01-Dec-2020

Introduction:

In this article we will explain how to achieve CURD operation in asp.net with Entity framework. Before getting started let’s know some basics about ASP.NET Core.

Description:

ASP.NET is a popular web-development framework for building web apps on the .NET platform.

ASP.NET Core is the open-source version of ASP.NET, that runs on macOS, Linux, and Windows. ASP.NET Core was first released in 2016 and is a re-design of earlier Windows-only versions of ASP.NET.

Now let’s create a demo to achieve CURD operation using asp.net core.

Create database following below script:

CREATE DATABASE collage
GO
USE collage
GO
CREATE TABLE [dbo].[Student](
[Id] [bigint] IDENTITY(1,1) primary key,
[Name] [varchar](30) NULL,
[Phone] [varchar](20) NULL,
[Address] [varchar](50) NULL,
[City] [varchar](30) NULL,
[Country] [varchar](30) NULL
)

 Creating an ASP.NET Core Project

Open Visual Studio 2017 and let’s create a new ASP.NET Core Web Application project. To do this, select File > New > Project. In the New Project dialog select Visual C# > Web > ASP.NET Core Web Application just like in the figure below:

crud operations in asp .net core with entity framework

Figure 1: ASP.NET Core Web Application Project Template

Name your project to whatever you like, but for this exercise, we will name it as “AspDotNetCoreApp” to confirm with the topic. Click OK and then select “Web Application” within ASP.NET Core templates as shown in the following figure below:

crud operations in asp .net core with entity framework

Figure 2: ASP.NET Core Web Application Template

Now click OK to let Visual Studio generate the required files needed for us to run the application. The figure below shows the default generated files:

crud operations in asp .net core with entity framework

Figure 3: Default ASP.NET Core Web Application Project Files

Create Model and Page

Let's create a “Models” folder within the root of the application and under that folder, create another folder and name it as “DataBase”. And also create student.cshtml and studentList.cshtml page inside pages folder .Our project structure should now look something like below:

crud operations in asp .net core with entity framework

Figure 4: The Models Folder and Pages

The “DataBase" folder will contain our DBContext and Entity models. We are going to use Entity Framework Core as our data access mechanism to work with database. We will not be using the old-fashioned Entity Framework designer to generate models for us because EF designer (EDMX) isn’t supported in ASP.NET Core 2.0

Integrating Entity Framework Core

Now, right-click on the root of your application and then select Manage NuGet Packages. Select the Browse tab and in the search bar, type in “Microsoft.EntityFrameworkCore.SqlServer”. It should result to something like this:

crud operations in asp .net core with entity framework

Figure 5: Manage NuGet Package

we are going to use Database-First development approach to work with existing database, we need to install the additional packages below as well:

  • Microsoft.EntityFrameworkCore.Tools (v2.0.1)
  •  Microsoft.EntityFrameworkCore.SqlServer.Design (v1.1.4)

Using Nuget Package Manager GUI

Go to Tools > NuGet Package Manager > Manage NuGet Packages for Solution, then type in "Microsoft.EntityFrameworkCore.Tools”. Click install and then do the same with "Microsoft.EntityFrameworkCore.Tools"." just like in the figure below:

crud operations in asp .net core with entity framework

Figure 6: Adding Microsoft.EntityFrameworkCore.Tools package

When it’s done installing all the required packages, you should be able to see them added to your project dependencies as shown in the figure below:

crud operations in asp .net core with entity framework

Figure 7: Entity Framework Core Packages installed

Creating Entity Models from Existing Database

 Using Package Manager Console

Go to Tools –> NuGet Package Manager –> Package Manager Console And then run the following command below to create a model from the existing database:

Scaffold-DbContext "Integrated
Security=SSPI;Persist Security Info=False;Initial Catalog=collage;Data Source=(local)"
Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models/DataBase

The Server attribute above is the SQL server instance name. You can find it in SQL Management Studio by right clicking on your database. For this example, the server name is “SSAI-L0028-HP\SQLEXPRESS”.

The Database attribute is your database name. In this case, the database name is “EFCoreDBFirstDemo”.

The –OutputDir attribute allows you to specify the location of the files generated. In this case, we’ve set it to Models/DataBase.

The command above will generate models from existing database within Models/DB folder. Here’s the screenshot below:

crud operations in asp .net core with entity framework

Figure 8: Entity Framework Generated Models

Now write code in student.cshtml.

Student.cshtml

@page
@model StudentModel
@{
    ViewData["Title"] = "Student"; Layout = "~/Pages/_Layout.cshtml"; }

 <div class="container">
    <h3>Add Student</h3>
    <hr />
    <br />
    <form method="post">
        <input asp-for="Student.Id" type="hidden" />
        <div class="row">
            <div class="col-md-4">
                <label asp-for="Student.Name"></label>
                <input asp-for="Student.Name" class="form-control" />
            </div>
        </div>
        <div class="row">
            <div class="col-md-4">
                <label asp-for="Student.Address"></label>
                <input asp-for="Student.Address" class="form-control" />
            </div>
        </div>
        <div class="row">
            <div class="col-md-4">
                <label asp-for="Student.Country"></label>
                <input asp-for="Student.Country" class="form-control" />
            </div>
        </div>
        <div class="row">
            <div class="col-md-4">
                <label asp-for="Student.City"></label>
                <input asp-for="Student.City" cl class="form-control" />
            </div>
        </div>
        <div class="row">
            <div class="col-md-4">
                <label asp-for="Student.Phone"></label>
                <input asp-for="Student.Phone" class="form-control" />
            </div>
        </div>
        <br />
        <input type="submit" value="Save" class="btn btn-primary" />
        <a class="btn btn-default" href="/StudentList">Cancel</a>
    </form>
</div>
@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

Following code write in student.html.cs (code behind)

Student.cshtml.cs 

using System;

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using AspDotNetCoreApp.Models.DataBase;

namespace AspDotNetCoreApp.Pages { public class StudentModel :PageModel {
        [BindProperty]
        public Student Student { get; set; }
        collageContext _context = new collageContext();
        public void OnGet(int? id)
        {
            if (id != null)
            {
                var data = (from student in _context.Student
                            where student.Id== id
                            select student).SingleOrDefault();
                Student = data;
            }
        }
        public ActionResult OnPost()
        {
            var student =Student;
            if(student.Id > 0)
              {
                _context.Entry(student).Property(x => x.Name).IsModified = true;
                _context.Entry(student).Property(x => x.Phone).IsModified = true;
                _context.Entry(student).Property(x => x.Address).IsModified = true;
                _context.Entry(student).Property(x => x.City).IsModified = true;
                _context.Entry(student).Property(x => x.Country).IsModified = true;
                _context.SaveChanges();
               }
            else
               {
                _context.Student.Add(student);
                _context.SaveChanges();
               }
          return RedirectToPage("StudentList");
        }
    }
}

Now write code in studentList.cshtml.

StudentList.cshtml

@page
@model AspDotNetCoreApp.Pages.StudentListModel
@{
    ViewData["Title"] = "StudentList";
    Layout = "~/Pages/_Layout.cshtml";
}
<div class="top-buffer"></div>
<div class="panel panel-primary">
    <div class="panel-heading panel-head">Students</div>
    <div class="panel-body">
        <div class="top-buffer"></div>
        <table class="table table-bordered table-striped table-condensed">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Contry</th>
                    <th>City</th>
                    <th>Phone</th>
                    <th>Address</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var item in Model.Students)
                {
                    <tr>
                        <td>@Html.DisplayFor(modelItem => item.Name)</td>
                        <td>@Html.DisplayFor(modelItem => item.Country)</td>
                        <td>@Html.DisplayFor(modelItem => item.City)</td>
                        <td>@Html.DisplayFor(modelItem => item.Phone)</td>
                        <td>@Html.DisplayFor(modelItem => item.Address)</td>
                         <td>
                             <a asp-page="./Student" asp-route-id="@item.Id">Edit</a>&nbsp;|&nbsp;
                             <a asp-page="./StudentList" asp-page-handler="Delete" asp-route-id="@item.Id">Delete</a>
                         </td>
                    </tr>
                }
            </tbody>
        </table>
    </div>
</div>
@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

Following code write in studentList.html.cs (code behind)

StudentList.cshtml.cs

using System;

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using AspDotNetCoreApp.Models.DataBase;
namespace AspDotNetCoreApp.Pages
{
    public class StudentListModel :PageModel
    {
        public List<Student> Students { get; set; }
        collageContext _context = new collageContext();
        public void OnGet()
        {
            Students =_context.Student.ToList();
        }
        public ActionResult OnGetDelete(int? id)
        {
            if (id != null)
            {
                var data = (from student in _context.Student
                            where student.Id== id
                            select student).SingleOrDefault();
                _context.Remove(data);
                _context.SaveChanges();
            }
            return RedirectToPage("StudentList");
        }
    }
}

Now build and run the application using CTRL + 5. In the browser, navigate to /student. It should bring up the following page.

crud operations in asp .net core with entity framework

Figure 9: The Create New Student Page

Fill all fields in the page and then click the Save button. It should take you to the StudentList page with the inserted data as shown in the figure below:

crud operations in asp .net core with entity framework

Figure 10: The StudentList Page

Of course the Edit and Delete works too without doing any code on your part.

I hope it will help to you.




Updated 01-Dec-2020
I am a content writter !

Leave Comment

Comments

Liked By