Thursday, October 10, 2019

ASP.NET Core And Entity Framework Core CRUD Operations

Entity Framework is an open-source framework which totally depends on ORM Framework (Object Relational Mapping). This framework gives an opportunity for the developer to work with data using different domain objects which specified in the model classes. For this doing this, they do not need to worried about considering about the tables or columns in the database in which data will be stored. 
So, Entity Framework provides a high level of abstraction to the developer for dealing with the data. Also, this framework provides the facility to the developer to develop the same application with less and compact code compare to the previous framework version. The following image illustrates the data procession structure for application where Entity Framework can be implemented.

FEATURES OF ENTITY FRAMEWORK

Before knowing how to work with Entity Framework Core, we first need to understand what the main features or advantages are 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 actually being a cross platform framework which can operate in any operating systems line Windows, Linux or Mac.
  • Model Class – Entity Framework always create an EDM model class on the basis of data objects. EDM means Entity Data Model. This model class always creates with get set properties for proper data types. This model classes are basically responsible for the data saving or fetching from the database.
  • Query – This framework always uses LINQ queries to fetch fata from the database. These LINQ queries is translate into the database based query (like SQL statement for RDBMS database) languages by the help of database provider. But we can also execute the actual SQL queries in to the database with this framework.
  • Saving - In Entity Framework, when we execute the SaveChanges() method, then the actual Insert, Update or Delete commands has been execute in to the database as per our model class or entities. This framework also called an asynchronous method of SaveChanges() which is known as SaveChangesAsync() method.
  • Transactions – Entity Framework maintain its own transaction management process which saving or fetching data from the database. Also, we can customize the transaction management as per our requirement in this framework.
  • Caching – Entity framework by default provide a caching layer for the data fetching concept. So, if we fetch the same data repeated time, then this framework returns those data from the cache instead of the hitting the database.
  • Configurations – Entity Framework always allow 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 which provided by this framework.

ABOUT ENTITY FRAMEWORK CORE

After releasing the first version of Entity Framework in 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 a stable framework whereas Entity Framework Core is a new Framework and still evolving with new features by the Microsoft and other Community.
  • Entity Framework Core can operate in any operating systems 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 operates for the .Net Framework 3.5 or above

STEPS TO CREATE WEBAPPS AND DATABASE

In this section, we will develop a simple web application using Entity Framework Core. For this, we will create an applications where basic CRUD operation can be performed for a Product Master. This section guides you through the step by step procedure how to create basic web application for the 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 New Submenu of File.
File=> New => Projects
Then Select Asp.Net Core Web Application from the Project List and Provide a Project Name (we are provide project name as SampleCoreEFPrjects) in the Name box and then click on OK Button.
After click on the OK Button, another popup window will opens where we need to select the Project Template type along with 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 OK Button.
Now, visual studio scaffolding the Asp.Net Core Project Structure and create the a project as below project structured.
In the project structure, there is a page called Index.cshtml which is basically created as per default project templates. We will change this page little bit for our applications later.

Step 2 – Create Product Table in 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 EDM model for the Product table which as per the above section. Now Create a folder Name Models in the Projects Structure. Now right on the folder and 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 creates 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.
Now, another window will open called 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
Now, the following pages has been added in the pages folder.
  1. Create.cshtml
  2. Edit.cshtml
  3. Details.cshtml
  4. Delete.cshtml
New Scaffold process also make some changes in the Startup.cs file as below –
Also, in the appSettings.json file, 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.
Now, in the above UI there are several buttons appeared for operate different operations –
  • Create New – This link button is used to create new product master. On click on this link button, create related UI interface will be open where we need to provide information and then save it.
  • Edit – This link button is used to perform edit operations on the existing records which shown in the index table list. On Edit button click, a new page called Edit view is opened with contains the selected records. We can change any data and then update that data in the database. After update, data automatically updated in 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 deteils.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");
 }
 }
}
SUMMARY
In this article, we discuss about the basic concept of Entity Framework along with its features or advantages. Also, we discuss about the new features of Entity Framework Core and shows how to create a simple CRUD operations using Entity Framework Core along with Razor pages in asp.net core.

No comments:

Post a Comment

No String Argument Constructor/Factory Method to Deserialize From String Value

  In this short article, we will cover in-depth the   JsonMappingException: no String-argument constructor/factory method to deserialize fro...