---
title: "crud operations in asp .net core with entity framework"  
description: "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 AS"  
author: "Anonymous User"  
published: 2020-12-01  
updated: 2020-12-01  
canonical: https://www.mindstick.com/articles/324872/crud-operations-in-asp-dot-net-core-with-entity-framework  
category: "asp.net core"  
tags: ["asp.net core", ".net core"]  
reading_time: 11 minutes  

---

# crud operations in asp .net core with entity framework

## Introduction:

In this article we will explain how to achieve CURD operation in asp.net with [Entity framework](https://www.mindstick.com/forum/12875/how-to-use-object-query-with-a-where-and-to-retrieve-entity-record-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 collageGOUSE collageGOCREATE 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](https://www.mindstick.com/forum/12863/how-to-insert-a-video-in-asp-dot-net-web-page-in-visual-studio-2010) 2017 and let’s create a new ASP.NET Core [Web Application](https://www.mindstick.com/interview/1126/does-silverlight-web-application-work-with-all-browsers) 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 mvc 5 with entity framework](https://www.mindstick.com/mindstickarticle/0d644caa-4ad7-4117-a85c-6c9731e4d9da/images/bdb44a28-e173-421e-a263-729f1d4d5e97.png)\

*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 mvc 5 with entity framework](https://www.mindstick.com/mindstickarticle/0d644caa-4ad7-4117-a85c-6c9731e4d9da/images/49e2855e-2391-4794-ac6d-f56312e87135.png)\

*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 mvc 5 with entity framework](https://www.mindstick.com/mindstickarticle/0d644caa-4ad7-4117-a85c-6c9731e4d9da/images/c50c500a-8cf7-4ec1-a89a-38a5d297f0f0.png)

*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 mvc 5 with entity framework](https://www.mindstick.com/mindstickarticle/0d644caa-4ad7-4117-a85c-6c9731e4d9da/images/7cbd044f-dd40-4ba8-8469-e9374ae4a089.png)

*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](https://www.mindstick.com/forum/159842/how-to-read-record-from-database-in-asp-mvc-core-using-entity-framework-core-1-0) 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](https://answers.mindstick.com/qa/97584/how-do-you-choose-the-correct-camera-for-your-application) and then select Manage [NuGet Packages](https://answers.mindstick.com/qa/31181/some-nuget-packages-were-installed-using-a-target-framework-different-from-the-current-target-framework-and-may-need-to-be-reinstalled). 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 mvc 5 with entity framework](https://www.mindstick.com/mindstickarticle/0d644caa-4ad7-4117-a85c-6c9731e4d9da/images/2f7aed8e-5947-4538-9e38-2e2a50b15956.png)

*Figure 5: Manage NuGet Package*

we are going to use Database-First development approach to work with [existing database](https://www.mindstick.com/forum/159905/how-can-i-generate-migrations-for-an-existing-database-in-dot-net-6), 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](https://answers.mindstick.com/qa/112022/what-are-the-advantages-of-using-a-package-manager-like-npm-or-yarn-in-javascript-development) 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 mvc 5 with entity framework](https://www.mindstick.com/mindstickarticle/0d644caa-4ad7-4117-a85c-6c9731e4d9da/images/2b11dc80-d4dd-44d2-8b1d-fe1f2853cb27.png)\

*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 mvc 5 with entity framework](https://www.mindstick.com/mindstickarticle/0d644caa-4ad7-4117-a85c-6c9731e4d9da/images/274a1dbf-3dab-4bd0-8da9-8d699601ea83.png)\

*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](https://answers.mindstick.com/qa/93946/how-to-rename-and-drop-a-database-form-sql-server-using-command-and-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](https://www.mindstick.com/mindstickarticle/0d644caa-4ad7-4117-a85c-6c9731e4d9da/images/8149944f-38ed-482e-8aec-332f9580d452.png)\

*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](https://www.mindstick.com/mindstickarticle/0d644caa-4ad7-4117-a85c-6c9731e4d9da/images/e027dde0-b493-4b9f-a87e-891a01ae9138.png)\

*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](https://www.mindstick.com/mindstickarticle/0d644caa-4ad7-4117-a85c-6c9731e4d9da/images/5c25b08d-00e8-49ef-bcab-31e0c96314d6.png)\

*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.

## \

## \

---

Original Source: https://www.mindstick.com/articles/324872/crud-operations-in-asp-dot-net-core-with-entity-framework

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
