ASP.NET Core And Entity Framework Core CRUD Operations

ASP.NET Core And Entity Framework Core CRUD Operations

20 Jun 2024
Intermediate
55.6K Views
69 min read
Learn via Video Course & by Doing Hands-on Labs

Self-Paced ASP.NET Core Course

ASP.NET Core And Entity Framework Core CRUD Operations

Entity Framework is an open-source framework that depends on ORM Framework (Object Relational Mapping). This framework allows the developer to work with data using different domain objects specified in the model classes. For this, they do not need to worry about the tables or columns in the database where data will be stored. So, Entity Framework provides a high level of abstraction to the developer for dealing with the data along with the facility for the developer to develop the same application with less compact code compared to the previous framework version.

The following image illustrates the data procession structure for applications where Entity Framework can be implemented. In this ASP.NET Core tutorial, you will learn to perform CRUD operations in Entity Framework Core from the very beginning. This tutorial will help you to learn Entity Framework Core so that you can start using it in your web application. To enhance your understanding of the Entity Framework Core, explore our ASP.NET Core Certification

ASP.NET Core And Entity Framework Core CRUD Operations

Features Of Entity Framework

Before knowing how to work with Entity Framework Core, we first need to understand the main features or advantages we can achieve if we are using this framework or technology. The main features of Entity Framework are

  • Cross Platform – This is the main difference between Entity Framework & ADO.Net. This framework is a cross-platform framework that can operate in any operating system like Windows, Linux, or Mac.

  • Model Class – Entity Framework always creates an EDM model class based on data objects. EDM means Entity Data Model. This model class always creates with get set properties for proper data types. These model classes are responsible for saving data or fetching from the database.

  • Query – This framework always uses LINQ queries to fetch data from the database. These LINQ queries are translated into database-based query (like SQL statements for RDBMS database) languages with the help of a database provider. But we can also execute the actual SQL queries into the database with this framework.

  • Saving - In Entity Framework, when we execute the SaveChanges() method, the actual Insert, Update, or Delete commands execute into the database as per our model class or entities. This framework is also called an asynchronous method of SaveChanges() which is known as the SaveChangesAsync() method.

  • Transactions – Entity Framework maintains its transaction management process which saves or fetches data from the database. Also, we can customize the transaction management as per our requirements in this framework.

  • Caching – Entity framework by default provides a caching layer for the data fetching concept. So, if we fetch the same data repeatedly time, it returns those data from the cache instead of hitting the database.

  • Configurations – Entity Framework always allows us to provide a configuration for the model class or entity class. We can use the data annotation attributes or Fluent API if we want to override the default conventions provided by this framework.

What is Entity Framework Core?

After releasing the first version of Entity Framework in the year of 2008, Microsoft released several versions of this framework till now. So, with the release of Asp.Net Core in the Year 2016, Microsoft also released a new version of the Entity Framework called Entity Framework Core. It has some new features over the Latest Entity Framework 6.0.

  • Entity Framework 6.0 is stable whereas Entity Framework Core is a new Framework and still evolving with new features by Microsoft and other Communities.

  • Entity Framework Core can operate in any operating system like Windows, Linux, etc. whereas Entity Framework 6 works only in Windows Operating Systems.

  • Entity Framework Core required .Net Framework 4.5 or above versions. But Entity Framework 6 can be operated for the .Net Framework 3.5 or above.

Steps To Create Web Apps and Database

This section will develop a simple web application using Entity Framework Core. For this, we will create an application where basic CRUD operations can be performed for a Product Master. This section guides you through the step-by-step procedure of how to create a basic web application for CRUD operations using Entity Framework in Asp.Net Core.

Prerequisites

  • Visual Studio 2017

  • .Net Core 2.1 SDK or Later

  • RDBMS Database Systems (SQL Server)

Step 1 - Create the Projects

Open Microsoft Visual Studio, then click on the Project option under the New Submenu of File.

File=> New => Projects

Then Select Asp.Net Core Web Application from the Project List and Provide a Project Name (we provide the project name as SampleCoreEFPrjects) in the Name box and then click on the OK Button.

After clicking on the OK Button, another popup window will open where we need to select the Project Template type along with the Asp.Net Core version. We will select Web Application Project template types along the Asp.Net Core 2.1 version in this window and then Click on the OK Button.

We will select Web Application Project template types along the Asp.Net Core 2.1 version in this window and then Click on the OK Button

Now, Visual Studio scaffolds the Asp.Net Core Project Structure and creates a project as the below project structure.

Now, Visual Studio scaffolds the Asp.Net Core Project Structure and creates a project as the below project structure.

In the project structure, there is a page called Index.cshtml which is created as per default project templates. We will change this page a little bit for our applications later.

Step 2 – Create a Product Table in the Database

Now, create the Product table in the SQL Server Database which contains the Below Columns- CREATE TABLE DBO.PRODUCT

(
Id
INT
NOT NULL
IDENTITY(1,1),
ProductCode
NVARCHAR(30)
NOT NULL,
ProductName
NVARCHAR(100)
NOT NULL,
Manufacturer
NVARCHAR(100)
NOT NULL,
ShippingNo
NVARCHAR(100)
NOT NULL,
SerialNo
INT
NULL,
BatchNo
NVARCHAR(100)
NOT NULL,
MRP
DECIMAL(18,2)
NOT NULL,
Quantity
INT
NOT NULL,
CreatedOn
DATETIME2
NOT NULL
DEFAULT GETDATE(),
LastModifiedOn
DATETIME2
NULL,
CONSTRAINT [PK_Product_Id]
PRIMARY KEY (Id)
)

Step 3 - Create Entity Data Model (EDM)

Now, it’s time to create an EDM model for the Product table which is as per the above section. Now Create a folder Name Models in the Projects Structure. Now right on the folder choose Add =>New Item and create a class file named Product.cs as below

Now Create a folder Name Models in the Projects Structure. Now right on the folder choose Add =>New Item and create a class file named Product.cs as below
Product.cs file code
using System;
using System.ComponentModel.DataAnnotations;

namespace SampleCoreEFPrjects.Models
{
 public class Products
 {
 public int Id { get; set; }
 [Display(Name = "Product Code")]
 public string ProductCode { get; set; }
 [Display(Name = "Product Name")]
 public string ProductName { get; set; }
 public string Manufacturer { get; set; }
 [Display(Name = "Shipping No")]
 public string ShippingNo { get; set; }
 [Display(Name = "Serial No")]
 public int SerialNo { get; set; }
 [Display(Name = "Batch No")]
 public string BatchNo { get; set; }
 [Display(Name = "Retail Price")]
 public decimal MRP { get; set; }
 public int Quantity { get; set; }
 [Display(Name = "Created On")]
 public DateTime? CreatedOn { get; set; }
 [Display(Name = "Modified On")]
 public DateTime? LastModifiedOn { get; set; }
 }
}

Step 4 - Scaffold the Product Model

Now, we will scaffold the Product model. This scaffold process will automatically create the pages for create, update, delete, and read operations for the Product models. So, now select the Pages folder and right click and select

Add => Razor Pages options

It will open the scaffold window where need to select Razor Pages using Entity Framework (CRUD) and then click on Add Button.

It will open the scaffold window where need to select Razor Pages using Entity Framework (CRUD) and then click on Add Button.

Now, another window will open called the Model Class window where we need to perform the following steps –

  • Select Product class from the Model Class drop-down

  • Click on plus (+) sign button and provide the name of the DataContext class as SampleCoreEFPrjects.Models.DataContext

  • Select the name SampleCoreEFPrjects.Models.DataContext from the Data Context Class dropdown.

  • Click on Add Button

Model Class window

Now, the following pages have been added to the pages folder.

  1. Create. cshtml

  2. Edit. cshtml

  3. Details. cshtml

  4. Delete. cshtml

The New Scaffold process also makes some changes in the Startup.cs file as below –

The New Scaffold process also makes some changes in the Startup.cs file as below

Also, in the appSettings.json file, a database connection string has been added. We need to change it as per our database name.

in the appSettings.json file, a database connection string has been added. We need to change it as per our database name

Now, we can run the code in the browser. This is the index page where product-wise listing is appeared after fetching data from the database tables.

Core Entity Framework Sample Demo

Now, in the above UI, there are several buttons for operating different operations –

  • Create New – This link button is used to create a new product master. On clicking on this link button, a related UI interface will open where we need to provide information and then save it.

  • create a new product master
  • Edit – This link button is used to perform edit operations on the existing records which are shown in the index table list. On clicking the Edit button, a new page called Edit view is opened which contains the selected records. We can change any data and then update that data in the database. After the update, data is automatically updated on the index page.

  • Details – This button is actually used to display the data in another view.

  • Delete – This option is used when we want to delete any record from the database. On click on the Delete button, it will open the delete view with data and a Delete Button. On Click on the Delete button in the Delete view, data will be deleted permanently from Database.

Code of Startup.cs
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;
using SampleCoreEFPrjects.Models;

namespace SampleCoreEFPrjects
{
 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_1);
 
 services.AddDbContext<DataContext>(options =>
 options.UseSqlServer(Configuration.GetConnectionString("DataContext")));
 }

 // 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("/Error");
 }

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

 app.UseMvc();
 }
 }
}

Code of index.cshtml

 @page
 @model SampleCoreEFPrjects.Pages.Product.IndexModel
 
 @{
 ViewData["Title"] = "Index";
 }
 
 
 <div class="row">
 <div class="page-header">
 <h1>Product Master Details</h1>
 </div>
 </div>
 
 <p>
 <a asp-page="Create">Create New</a>
 </p>
 <table class="table">
 <thead>
 <tr>
 <th>
 @Html.DisplayNameFor(model => model.Product[0].ProductCode)
 </th>
 <th>
 @Html.DisplayNameFor(model => model.Product[0].ProductName)
 </th>
 <th>
 @Html.DisplayNameFor(model => model.Product[0].Manufacturer)
 </th>
 <th>
 @Html.DisplayNameFor(model => model.Product[0].ShippingNo)
 </th>
 <th>
 @Html.DisplayNameFor(model => model.Product[0].SerialNo)
 </th>
 <th>
 @Html.DisplayNameFor(model => model.Product[0].BatchNo)
 </th>
 <th>
 @Html.DisplayNameFor(model => model.Product[0].MRP)
 </th>
 <th>
 @Html.DisplayNameFor(model => model.Product[0].Quantity)
 </th>
 <th>
 @Html.DisplayNameFor(model => model.Product[0].CreatedOn)
 </th>
 <th>
 @Html.DisplayNameFor(model => model.Product[0].LastModifiedOn)
 </th>
 <th></th>
 </tr>
 </thead>
 <tbody>
 @foreach (var item in Model.Product)
 {
 <tr>
 <td>
 @Html.DisplayFor(modelItem => item.ProductCode)
 </td>
 <td>
 @Html.DisplayFor(modelItem => item.ProductName)
 </td>
 <td>
 @Html.DisplayFor(modelItem => item.Manufacturer)
 </td>
 <td>
 @Html.DisplayFor(modelItem => item.ShippingNo)
 </td>
 <td>
 @Html.DisplayFor(modelItem => item.SerialNo)
 </td>
 <td>
 @Html.DisplayFor(modelItem => item.BatchNo)
 </td>
 <td>
 @Html.DisplayFor(modelItem => item.MRP)
 </td>
 <td>
 @Html.DisplayFor(modelItem => item.Quantity)
 </td>
 <td>
 @Html.DisplayFor(modelItem => item.CreatedOn)
 </td>
 <td>
 @Html.DisplayFor(modelItem => item.LastModifiedOn)
 </td>
 <td>
 <a asp-page="./Edit" asp-route-id="@item.Id">Edit</a> |
 <a asp-page="./Details" asp-route-id="@item.Id">Details</a> |
 <a asp-page="./Delete" asp-route-id="@item.Id">Delete</a>
 </td>
 </tr>
 }
 </tbody>
 </table>

Code of index.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 Microsoft.EntityFrameworkCore;
using SampleCoreEFPrjects.Models;

namespace SampleCoreEFPrjects.Pages.Product
{
 public class IndexModel : PageModel
 {
 private readonly SampleCoreEFPrjects.Models.DataContext _context;

 public IndexModel(SampleCoreEFPrjects.Models.DataContext context)
 {
 _context = context;
 }

 public IList<Products> Product { get;set; }

 public async Task OnGetAsync()
 {
 Product = await _context.Product.ToListAsync();
 }
 }
}

Code of Create.cshtml

 @page
 @model SampleCoreEFPrjects.Pages.Product.CreateModel
 
 @{
 ViewData["Title"] = "Create";
 }
 
 <h2>Create</h2>
 
 <h4>Product</h4>
 <hr />
 <div class="row">
 <div class="col-md-4">
 <form method="post">
 <div asp-validation-summary="ModelOnly" class="text-danger"></div>
 <div class="form-group">
 <label asp-for="Product.ProductCode" class="control-label"></label>
 <input asp-for="Product.ProductCode" class="form-control" />
 <span asp-validation-for="Product.ProductCode" class="text-danger"></span>
 </div>
 <div class="form-group">
 <label asp-for="Product.ProductName" class="control-label"></label>
 <input asp-for="Product.ProductName" class="form-control" />
 <span asp-validation-for="Product.ProductName" class="text-danger"></span>
 </div>
 <div class="form-group">
 <label asp-for="Product.Manufacturer" class="control-label"></label>
 <input asp-for="Product.Manufacturer" class="form-control" />
 <span asp-validation-for="Product.Manufacturer" class="text-danger"></span>
 </div>
 <div class="form-group">
 <label asp-for="Product.ShippingNo" class="control-label"></label>
 <input asp-for="Product.ShippingNo" class="form-control" />
 <span asp-validation-for="Product.ShippingNo" class="text-danger"></span>
 </div>
 <div class="form-group">
 <label asp-for="Product.SerialNo" class="control-label"></label>
 <input asp-for="Product.SerialNo" class="form-control" />
 <span asp-validation-for="Product.SerialNo" class="text-danger"></span>
 </div>
 <div class="form-group">
 <label asp-for="Product.BatchNo" class="control-label"></label>
 <input asp-for="Product.BatchNo" class="form-control" />
 <span asp-validation-for="Product.BatchNo" class="text-danger"></span>
 </div>
 <div class="form-group">
 <label asp-for="Product.MRP" class="control-label"></label>
 <input asp-for="Product.MRP" class="form-control" />
 <span asp-validation-for="Product.MRP" class="text-danger"></span>
 </div>
 <div class="form-group">
 <label asp-for="Product.Quantity" class="control-label"></label>
 <input asp-for="Product.Quantity" class="form-control" />
 <span asp-validation-for="Product.Quantity" class="text-danger"></span>
 </div>
 <div class="form-group">
 <input type="submit" value="Create" class="btn btn-default" />
 </div>
 </form>
 </div>
 </div>
 
 <div>
 <a asp-page="Index">Back to List</a>
 </div>
 
 @section Scripts {
 @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
 }

Code of Create.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 Microsoft.AspNetCore.Mvc.Rendering;
using SampleCoreEFPrjects.Models;

namespace SampleCoreEFPrjects.Pages.Product
{
 public class CreateModel : PageModel
 {
 private readonly SampleCoreEFPrjects.Models.DataContext _context;

 public CreateModel(SampleCoreEFPrjects.Models.DataContext context)
 {
 _context = context;
 }

 public IActionResult OnGet()
 {
 return Page();
 }

 [BindProperty]
 public Products Product { get; set; }

 public async Task<IActionResult>OnPostAsync()
 {
 if (!ModelState.IsValid)
 {
 return Page();
 }
 Product.CreatedOn = DateTime.Now;
 _context.Product.Add(Product);
 await _context.SaveChangesAsync();

 return RedirectToPage("./Index");
 }
 }
}

Code of edit.cshtml

 @page
 @model SampleCoreEFPrjects.Pages.Product.EditModel
 
 @{
 ViewData["Title"] = "Edit";
 }
 
 <h2>Edit</h2>
 
 <h4>Product</h4>
 <hr />
 <div class="row">
 <div class="col-md-4">
 <form method="post">
 <div asp-validation-summary="ModelOnly" class="text-danger"></div>
 <input type="hidden" asp-for="Product.Id" />
 <div class="form-group">
 <label asp-for="Product.ProductCode" class="control-label"></label>
 <input asp-for="Product.ProductCode" class="form-control" />
 <span asp-validation-for="Product.ProductCode" class="text-danger"></span>
 </div>
 <div class="form-group">
 <label asp-for="Product.ProductName" class="control-label"></label>
 <input asp-for="Product.ProductName" class="form-control" />
 <span asp-validation-for="Product.ProductName" class="text-danger"></span>
 </div>
 <div class="form-group">
 <label asp-for="Product.Manufacturer" class="control-label"></label>
 <input asp-for="Product.Manufacturer" class="form-control" />
 <span asp-validation-for="Product.Manufacturer" class="text-danger"></span>
 </div>
 <div class="form-group">
 <label asp-for="Product.ShippingNo" class="control-label"></label>
 <input asp-for="Product.ShippingNo" class="form-control" />
 <span asp-validation-for="Product.ShippingNo" class="text-danger"></span>
 </div>
 <div class="form-group">
 <label asp-for="Product.SerialNo" class="control-label"></label>
 <input asp-for="Product.SerialNo" class="form-control" />
 <span asp-validation-for="Product.SerialNo" class="text-danger"></span>
 </div>
 <div class="form-group">
 <label asp-for="Product.BatchNo" class="control-label"></label>
 <input asp-for="Product.BatchNo" class="form-control" />
 <span asp-validation-for="Product.BatchNo" class="text-danger"></span>
 </div>
 <div class="form-group">
 <label asp-for="Product.MRP" class="control-label"></label>
 <input asp-for="Product.MRP" class="form-control" />
 <span asp-validation-for="Product.MRP" class="text-danger"></span>
 </div>
 <div class="form-group">
 <label asp-for="Product.Quantity" class="control-label"></label>
 <input asp-for="Product.Quantity" class="form-control" />
 <span asp-validation-for="Product.Quantity" class="text-danger"></span>
 </div>
 <div class="form-group">
 <label asp-for="Product.CreatedOn" class="control-label"></label>
 <input asp-for="Product.CreatedOn" class="form-control" readonly />
 <span asp-validation-for="Product.CreatedOn" class="text-danger"></span>
 </div>
 <div class="form-group">
 <input type="submit" value="Save" class="btn btn-default" />
 </div>
 </form>
 </div>
 </div>
 
 <div>
 <a asp-page="./Index">Back to List</a>
 </div>
 
 @section Scripts {
 @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
 }

Code of edit.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 Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using SampleCoreEFPrjects.Models;

namespace SampleCoreEFPrjects.Pages.Product
{
 public class EditModel : PageModel
 {
 private readonly SampleCoreEFPrjects.Models.DataContext _context;

 public EditModel(SampleCoreEFPrjects.Models.DataContext context)
 {
 _context = context;
 }

 [BindProperty]
 public Products Product { get; set; }

 public async Task<IActionResult> OnGetAsync(int? id)
 {
 if (id == null)
 {
 return NotFound();
 }

 Product = await _context.Product.FirstOrDefaultAsync(m => m.Id == id);

 if (Product == null)
 {
 return NotFound();
 }
 return Page();
 }

 public async Task<IActionResult> OnPostAsync()
 {
 if (!ModelState.IsValid)
 {
 return Page();
 }

 Product.LastModifiedOn = DateTime.Now;
 _context.Attach(Product).State = EntityState.Modified;

 try
 {
 await _context.SaveChangesAsync();
 }
 catch (DbUpdateConcurrencyException)
 {
 if (!ProductExists(Product.Id))
 {
 return NotFound();
 }
 else
 {
 throw;
 }
 }

 return RedirectToPage("./Index");
 }

 private bool ProductExists(int id)
 {
 return _context.Product.Any(e => e.Id == id);
 }
 }
}

Code of details.cshtml

@page
 @model SampleCoreEFPrjects.Pages.Product.DetailsModel
 
 @{
 ViewData["Title"] = "Details";
 }
 
 <h2>Details</h2>
 
 <div>
 <h4>Product</h4>
 <hr />
 <dl class="dl-horizontal">
 <dt>
 @Html.DisplayNameFor(model => model.Product.ProductCode)
 </dt>
 <dd>
 @Html.DisplayFor(model => model.Product.ProductCode)
 </dd>
 <dt>
 @Html.DisplayNameFor(model => model.Product.ProductName)
 </dt>
 <dd>
 @Html.DisplayFor(model => model.Product.ProductName)
 </dd>
 <dt>
 @Html.DisplayNameFor(model => model.Product.Manufacturer)
 </dt>
 <dd>
 @Html.DisplayFor(model => model.Product.Manufacturer)
 </dd>
 <dt>
 @Html.DisplayNameFor(model => model.Product.ShippingNo)
 </dt>
 <dd>
 @Html.DisplayFor(model => model.Product.ShippingNo)
 </dd>
 <dt>
 @Html.DisplayNameFor(model => model.Product.SerialNo)
 </dt>
 <dd>
 @Html.DisplayFor(model => model.Product.SerialNo)
 </dd>
 <dt>
 @Html.DisplayNameFor(model => model.Product.BatchNo)
 </dt>
 <dd>
 @Html.DisplayFor(model => model.Product.BatchNo)
 </dd>
 <dt>
 @Html.DisplayNameFor(model => model.Product.MRP)
 </dt>
 <dd>
 @Html.DisplayFor(model => model.Product.MRP)
 </dd>
 <dt>
 @Html.DisplayNameFor(model => model.Product.Quantity)
 </dt>
 <dd>
 @Html.DisplayFor(model => model.Product.Quantity)
 </dd>
 <dt>
 @Html.DisplayNameFor(model => model.Product.CreatedOn)
 </dt>
 <dd>
 @Html.DisplayFor(model => model.Product.CreatedOn)
 </dd>
 <dt>
 @Html.DisplayNameFor(model => model.Product.LastModifiedOn)
 </dt>
 <dd>
 @Html.DisplayFor(model => model.Product.LastModifiedOn)
 </dd>
 </dl>
 </div>
 <div>
 <a asp-page="./Edit" asp-route-id="@Model.Product.Id">Edit</a> |
 <a asp-page="./Index">Back to List</a>
 </div>

Code of details.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 Microsoft.EntityFrameworkCore;
using SampleCoreEFPrjects.Models;

namespace SampleCoreEFPrjects.Pages.Product
{
 public class DetailsModel : PageModel
 {
 private readonly SampleCoreEFPrjects.Models.DataContext _context;

 public DetailsModel(SampleCoreEFPrjects.Models.DataContext context)
 {
 _context = context;
 }

 public Products Product { get; set; }

 public async Task<IActionResult> OnGetAsync(int? id)
 {
 if (id == null)
 {
 return NotFound();
 }

 Product = await _context.Product.FirstOrDefaultAsync(m => m.Id == id);

 if (Product == null)
 {
 return NotFound();
 }
 return Page();
 }
 }
}

Code of delete.cshtml

 @page
 @model SampleCoreEFPrjects.Pages.Product.DeleteModel
 
 @{
 ViewData["Title"] = "Delete";
 }
 
 <h2>Delete</h2>
 
 <h3>Are you sure you want to delete this?</h3>
 <div>
 <h4>Product</h4>
 <hr />
 <dl class="dl-horizontal">
 <dt>
 @Html.DisplayNameFor(model => model.Product.ProductCode)
 </dt>
 <dd>
 @Html.DisplayFor(model => model.Product.ProductCode)
 </dd>
 <dt>
 @Html.DisplayNameFor(model => model.Product.ProductName)
 </dt>
 <dd>
 @Html.DisplayFor(model => model.Product.ProductName)
 </dd>
 <dt>
 @Html.DisplayNameFor(model => model.Product.Manufacturer)
 </dt>
 <dd>
 @Html.DisplayFor(model => model.Product.Manufacturer)
 </dd>
 <dt>
 @Html.DisplayNameFor(model => model.Product.ShippingNo)
 </dt>
 <dd>
 @Html.DisplayFor(model => model.Product.ShippingNo)
 </dd>
 <dt>
 @Html.DisplayNameFor(model => model.Product.SerialNo)
 </dt>
 <dd>
 @Html.DisplayFor(model => model.Product.SerialNo)
 </dd>
 <dt>
 @Html.DisplayNameFor(model => model.Product.BatchNo)
 </dt>
 <dd>
 @Html.DisplayFor(model => model.Product.BatchNo)
 </dd>
 <dt>
 @Html.DisplayNameFor(model => model.Product.MRP)
 </dt>
 <dd>
 @Html.DisplayFor(model => model.Product.MRP)
 </dd>
 <dt>
 @Html.DisplayNameFor(model => model.Product.Quantity)
 </dt>
 <dd>
 @Html.DisplayFor(model => model.Product.Quantity)
 </dd>
 <dt>
 @Html.DisplayNameFor(model => model.Product.CreatedOn)
 </dt>
 <dd>
 @Html.DisplayFor(model => model.Product.CreatedOn)
 </dd>
 <dt>
 @Html.DisplayNameFor(model => model.Product.LastModifiedOn)
 </dt>
 <dd>
 @Html.DisplayFor(model => model.Product.LastModifiedOn)
 </dd>
 </dl>
 
 <form method="post">
 <input type="hidden" asp-for="Product.Id" />
 <input type="submit" value="Delete" class="btn btn-default" /> |
 <a asp-page="./Index">Back to List</a>
 </form>
 </div>

Code of delete.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 Microsoft.EntityFrameworkCore;
using SampleCoreEFPrjects.Models;

namespace SampleCoreEFPrjects.Pages.Product
{
 public class DeleteModel : PageModel
 {
 private readonly SampleCoreEFPrjects.Models.DataContext _context;

 public DeleteModel(SampleCoreEFPrjects.Models.DataContext context)
 {
 _context = context;
 }

 [BindProperty]
 public Products Product { get; set; }

 public async Task<IActionResult> OnGetAsync(int? id)
 {
 if (id == null)
 {
 return NotFound();
 }

 Product = await _context.Product.FirstOrDefaultAsync(m => m.Id == id);

 if (Product == null)
 {
 return NotFound();
 }
 return Page();
 }

 public async Task<IActionResult> OnPostAsync(int? id)
 {
 if (id == null)
 {
 return NotFound();
 }

 Product = await _context.Product.FindAsync(id);

 if (Product != null)
 {
 _context.Product.Remove(Product);
 await _context.SaveChangesAsync();
 }

 return RedirectToPage("./Index");
 }
 }
}

Build your Entity Framework Core Application

To build your Entity Framework Core Application, you need to follow some basic steps that are as follows:
  1. Set up your ASP.NET Core Project- First of all, create your new project using Visual Studio or .NET CLI with proper tools and the needed SDK installed.
    dotnet new web -n MyEFCoreApp
    cd MyEFCoreApp
    
  2. Install Entity Framework Core- Next, you need to install the Entity Framework Core.
    dotnet add package Microsoft.EntityFrameworkCore.SqlServer
    
  3. Define Data Model- Create entity classes to define your data model which will represent the entities of the domain.
    public class Post
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }
        public DateTime CreatedAt { get; set; }
        // Other properties and relationships
    }
    
    public class Comment
    {
        public int Id { get; set; }
        public string Text { get; set; }
        public DateTime CreatedAt { get; set; }
        // Other properties and relationships
    }
    
  4. Configure DbContext- Now, you need to showcase the database of your application, For that purpose, create a custom 'DbContext.
    public class AppDbContext : DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
    
        public DbSet Posts { get; set; }
        public DbSet<Comment> Comments { get; set; }
    
        // Other configurations and relationships
    }
    
  5. Migrations and Database Setup- Now that you have successfully defined the data model, you can generate the migrations and using them create the database schema or update it.
    dotnet ef migrations add InitialCreate
    dotnet ef database update
    
  6. Implement CRUD Operations- Finally, you are all ready to perform CRUD operations using EF Core as you need.
    using (var context = new AppDbContext(options))
    {
        var newPost = new Post { Title = "New Post", Content = "Content of the new post" };
        context.Posts.Add(newPost);
        context.SaveChanges();
    }
    

Add Your Entity Framework Core Data Layer

Now that you have successfully completed building up of your Entity Framework Core Application, you can move onto creating the data layer for it. For that you will need to implement repository pattern that will help in separating data access logic from the other components. Let us have a look at this example to comprehend the creation of our Entity Framework Core Data Layer in deep.

Example:

// Define IRepository interface for generic CRUD operations
public interface IRepository<TEntity> where TEntity : class
{
    Task<IEnumerable<TEntity>> GetAllAsync();
    Task<TEntity> GetByIdAsync(int id);
    Task<TEntity> AddAsync(TEntity entity);
    Task<TEntity> UpdateAsync(TEntity entity);
    Task<bool> DeleteAsync(int id);
}

// Implement the Repository class, utilizing EF Core for data operations
public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
    private readonly AppDbContext _context;

    public Repository(AppDbContext context)
    {
        _context = context;
    }

    public async Task<IEnumerable<TEntity>> GetAllAsync() =>
        await _context.Set<TEntity>().ToListAsync();

    // Implement other repository methods: GetByIdAsync, AddAsync, UpdateAsync, DeleteAsync
}

// Configure dependency injection in Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<AppDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
}

// Utilize repositories in controllers through dependency injection
public class PostController : Controller
{
    private readonly IRepository<Post> _postRepository;

    public PostController(IRepository<Post> postRepository)
    {
        _postRepository = postRepository;
    }

    public async Task<IActionResult> Index()
    {
        var posts = await _postRepository.GetAllAsync();
        return View(posts);
    }

    // Implement other controller actions for CRUD operations
}

Entity Framework Core and ASP.NET Core Web APIs

We can also integrate Entity Framework Core into ASP.NET Core Web APIs that will help in making the backend services more powerful and efficient.
To do that first, you need set up the ASP.NET Core Web API Project.
dotnet new webapi -n MyWebAPI
cd MyWebAPI
Now, install the Entity Framework Core NuGet packages for the the database provider you wish to work with. Here, we have used SQL Server
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
Define the data model entities as usual and also the DbContext class for EF Core needs to be configured at this step.
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }

    public DbSet<Product> Products { get; set; }
}
Also configure all the repositories present for dependency injection in the Startup.cs class.
public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<AppDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    // Register repositories or services
}
Now you can create the API controllers that will help in handling CRUD operations for the entities.
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    private readonly AppDbContext _context;

    public ProductsController(AppDbContext context)
    {
        _context = context;
    }

    [HttpGet]
    public async Task<ActionResult<IEnumerable<Product>>> GetProducts()
    {
        var products = await _context.Products.ToListAsync();
        return Ok(products);
    }

    // Implement other CRUD operations: GetById, Post, Put, Delete
}
Lastly, you can test your ASP.NET Core Web API project to ensure all the operations are properly as they should or not.

Testing Entity Framework Core in ASP.NET Core Applications

Testing is the most crucial part for building any kind of Web application as it lets the developer know that everything is working properly and all the operations are executed as they need to be so that if there's any error, it can be quickly corrected before deploying it to the audience. Same is with our ASP.NET Core Applications, we need to perform testing of our Entity Framework Core.
There are various strategies that will help us perform testing on our Entity Framework Core.
  • First one is Unit Testing with the help of an in-memory database provider that will do quick and isolated tests without actually interacting with the database.
  • Another one is Integration testing to test EF Core against real database.
  • You can tools like Moqs to isolate controllers from database dependencies.
SUMMARY

In this ASP.NET Core Training Online article, we discussed the basic concepts of Entity Framework along with its features or advantages. Also, we discussed the new features of Entity Framework Core and simple CRUD operations using Entity Framework Core along with Razor pages in asp.net core.

FAQs

Q1. What is meant by CRUD operations?

CRUD is Create, Read, Update and Delete.

Q2. What are the features of Entity Framework?

Cross Platform, Model Class, Query, Saving, Transactions, Caching, Configurations

Q3. How to create a basic web application for CRUD operations using Entity Framework in Asp.Net Core?

  • Visual Studio 2017
  • .Net Core 2.1 SDK or Later
  • RDBMS Database Systems (SQL Server)

Q4. What are CRUD operations in asp net with Entity Framework?

CRUD operations in ASP.NET with Entity Framework are those basic actions that are performed on a database, that are, Create, Read, Update and Delete.

Q5. What is CRUD operations in .NET Core?

CRUD operations in .NET Core can be simply referred to as Create, Read, Update and Delete. These are the operations performed on the data in a .NET Core application.

Take our Aspnet skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

GET FREE CHALLENGE

Share Article

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
.NET Solution Architect Certification Training Jul 28 SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification Training Jul 28 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
ASP.NET Core Certification Training Jul 28 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
ASP.NET Core Project Aug 24 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Debasis Saha (Technical Manager, Author and Mentor)

He is an ASP.Net, MVC and Angular Technical Manager with 10 years of experience. He always been a great fan of Microsoft Technologies and loves working on them. He has expertise in Asp.Net, MVC, SQL Server, MongoDB, Angular JS, and Angular. He loves to write articles about these technologies.
Accept cookies & close this