Introduction
This article introduces how to perform the Create, Read, Update, and Delete (CRUD) operations in ASP.NET Core, using Entity Framework Core. We will use the "Code First" development approach and create a database from model using migration. We can view this article’s sample on TechNet Gallery. I would like to recommend the following the article Overview Of ASP.NET Core so that we start development for this sample application in ASP.NET Core. We will create a single entity Customer to perform the CRUD operations.
Create Database
First, let's install the Entity Framework Core in our application. As we use SQL Server, install the package for SQL Server database provider. To install database provider, follow the below steps.
- Tools - NuGet Package Manager - Package Manager Console.
- Run PM> Install-Package Microsoft.EntityFrameworkCore.SqlServer.
When we install a package in ASP.NET Core application, then the package installation occurs in the background. We see "(Restoring...)" appeared next to References in Solution Explorer while the installation occurs.
We also use Entity Framework Core as an Object Relationship Mapper (ORM) to perform the CRUD operations. Let's install the Entity Framework Core Tool to maintain the database, using the following procedure.
- Run PM> Install-Package Microsoft.EntityFrameworkCore.Tools –Pre.
- Open project.json file.
- Locate the tools section and add the ef command as shown below.
{ "tools": { "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final", "BundlerMinifier.Core": "2.0.238", "Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final", "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final" } }
Now, create two entities - the BaseEntity class that has common properties that will be inherited by each entity, and the Customer. Let's see each entity. The following is a code snippet for the BaseEntity class.
using System;
namespace CRUDApplication.DbEntities
{
public class BaseEntity
{
public long Id { get; set; }
public DateTime AddedDate { get; set; }
public DateTime ModifiedDate { get; set; }
public string IPAddress { get; set; }
}
}
Now, create a Customer entity under the DbEntities folder which inherits from the BaseEntity class. The following is a code for Customer entity.
namespace CRUDApplication.DbEntities
{
public class Customer : BaseEntity
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string MobileNo { get; set; }
}
}
Now, let's define the configuration for the Customer entity that will be used when the database table will be created by the entity. The following is the code for Customer mapping entity (CustomerMap.cs).
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace CRUDApplication.DbEntities
{
public class CustomerMap
{
public CustomerMap(EntityTypeBuilder<Customer> entityBuilder)
{
entityBuilder.HasKey(t => t.Id);
entityBuilder.Property(t => t.FirstName).IsRequired();
entityBuilder.Property(t => t.LastName).IsRequired();
entityBuilder.Property(t => t.Email).IsRequired();
entityBuilder.Property(t => t.MobileNo).IsRequired();
}
}
}
The EntityTypeBuilder<T> is an important class that allows configuration to be performed for an entity type in a model. This is done using the modelbuilder in an override of the OnModelCreating method. The Constructor of the CustomerMap class uses the Fluent API to map and configure properties in the table. So let's see each method used in the constructor one-by-one.
- HasKey():The Haskey() method configures a primary key on table.
- Property():The Property method configures attributes for each property belonging to an entity or complex type. It is used to obtain a configuration object for a given property. The options on the configuration object are specific to the type being configured.
Now, it’s time to define context class. The ADO.NET Entity Framework Code First development approach requires us to create a data access context class that inherits from the DbContext class so we create a context class CRUDContext (CRUDContext.cs) class. In this class, we override the OnModelCreating() method. This method is called when the model for a context class (CRUDContext) has been initialized, but before the model has been locked down and used to initialize the context such that the model can be further configured before it is locked down. The following is the code snippet for the context class.
using Microsoft.EntityFrameworkCore;
namespace CRUDApplication.DbEntities
{
public class CRUDContext : DbContext
{
public CRUDContext(DbContextOptions<CRUDContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
new CustomerMap(modelBuilder.Entity<Customer>());
}
}
}
As the concept of dependency injection is central to the ASP.NET Core application, so we register our context to dependency injection during the application start up. Once we register CRUDContext context as a service to dependency injection, then provide it via constructor to MVC controller. In order for our MVC controllers to make use of CRUDContext, we are going to register it as a service.
- Open the appsettings.json file and define connection string here.
It stores application level settings such as connection string, SMTP etc. It’s similar to web.config file in ASP.NET.{ "ConnectionStrings": { "DefaultConnection": "Data Source=ADMIN\\SQLEXPRESS;Initial Catalog=ECommerceDb;User ID=sa; Password=*****" }, "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Debug", "System": "Information", "Microsoft": "Information" } } } - Open the Startup.cs file and following using statements at the start of the file.
using Microsoft.EntityFrameworkCore; using CRUDApplication.DbEntities; - Now, we can use the AddDbContext method to register it as a service. Locate the ConfigureServices method and add the lines of code for register it to dependency injection as per following code snippet.
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddDbContext<CRUDContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); }Now we have created model so time to create database using migration.
- Tools –> NuGet Package Manager –> Package Manager Console.
- Run PM> Add-Migration MyFirstMigration to scaffold a migration to create the initial set of tables for our model. If we receive an error stating the term ‘add-migration’ is not recognized as the name of a cmdlet, then close and reopen Visual Studio.
- Run PM> Update-Database to apply the new migration to the database. Because our database doesn’t exist yet, it will be created for us before the migration is applied.
Create Application User Interface
Now we proceed to the controller. Create a CustomerController under the Controllers folder of the application. This controller has all ActionResult methods for each user interface of a CRUD operation. We first create a CRUDContext class instance then we inject it in the controller's constructor to get its object. The following is a code snippet for the CustomerController.
using CRUDApplication.DbEntities;
using CRUDApplication.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
namespace CRUDApplication.Controllers
{
public class CustomerController : Controller
{
private readonly CRUDContext context;
public CustomerController(CRUDContext context)
{
this.context = context;
}
[HttpGet]
public IActionResult Index()
{
IEnumerable<CustomerViewModel> model = context.Set<Customer>()
.ToList()
.Select(s => new CustomerViewModel
{
Id = s.Id,
Name = $"{s.FirstName} {s.LastName}",
MobileNo = s.MobileNo,
Email = s.Email
});
return View("Index", model);
}
[HttpGet]
public IActionResult AddEditCustomer(long? id)
{
CustomerViewModel model = new CustomerViewModel();
if (id.HasValue)
{
Customer customer = context.Set<Customer>().SingleOrDefault(c => c.Id == id.Value);
if (customer != null)
{
model.Id = customer.Id;
model.FirstName = customer.FirstName;
model.LastName = customer.LastName;
model.MobileNo = customer.MobileNo;
model.Email = customer.Email;
}
}
return PartialView("~/Views/Customer/_AddEditCustomer.cshtml", model);
}
[HttpPost]
public ActionResult AddEditCustomer(long? id, CustomerViewModel model)
{
try
{
if (ModelState.IsValid)
{
bool isNew = !id.HasValue;
Customer customer = isNew ? new Customer
{
AddedDate = DateTime.UtcNow
} : context.Set<Customer>().SingleOrDefault(s => s.Id == id.Value);
if (customer != null)
{
customer.FirstName = model.FirstName;
customer.LastName = model.LastName;
customer.MobileNo = model.MobileNo;
customer.Email = model.Email;
customer.IPAddress = Request.HttpContext.Connection.RemoteIpAddress.ToString();
customer.ModifiedDate = DateTime.UtcNow;
if (isNew)
{
context.Add(customer);
}
context.SaveChanges();
}
}
}
catch (Exception ex)
{
throw ex;
}
return RedirectToAction("Index");
}
[Htt




Anandu G NathPosted Jan 23, 2024, 7:17 AM
Bro this is an incomplete article
Nandani MishraPosted Sep 20, 2022, 11:35 AM
I have not found _Modal and BootstrapModel in your demo, so please give me solution of this and _modelfooter and _modelheader can you elobrate please
Sandeep SiddhaparaPosted Jul 31, 2020, 12:42 AM
Unable to find ModalFooter Class, kindly let me know how to access it.
Vipul PatdiyaPosted Jul 31, 2020, 12:15 AM
I have not found _Modal and BootstrapModel in your demo, so please give me solution of this.
Ranjan RazzPosted Jul 10, 2020, 1:49 PM
Your article is very bad.
Nabeel Ur Rehaman ShahPosted Jan 15, 2020, 4:55 PM
Where is Database script file of this project
Володимир ГаврилюкPosted Jul 9, 2019, 2:26 PM
Hello. I'm getting CS0246 The type or namespace name 'ModalHeader' could not be found (are you missing a using directive or an assembly reference?)
Goutham VegesnaPosted Sep 24, 2018, 7:59 AM
It is returning an error that "The type or namespace name 'code' does not exist in the namespace 'Crudoperations' (are you missing an assembly reference?) [C:\Users\goutham\Documents\Crudoperations\Crudoperations.csproj]"
Mohamed rafeequePosted May 10, 2018, 3:28 AM
Project.json not found
Rizwan AhmedPosted Oct 4, 2017, 8:11 AM
I try to make this modal in my project like that but its not working . when i click on button its show the empty modal directly not go to server side and load the partial view into modal please help me .. thanks
Cliff Adams BitrusPosted Jun 15, 2017, 4:49 AM
I desperately and urgently need help on the following. I am developing a Web API. So far, I have successfully gotten the CRUD operations to execute using .NET Core with EF 1.1. However, when I update a record and then retrieve it, I keep getting the old version of the record not the currently updated one. On the database table, the updated record is correct, but the retrieved version of it using the Web API is incorrect. When I stop the Web Service and start it, I get the correct version. Can anyone help; how can I always get the most real-time correct version of a record using the Web API? The Web API is to be used by a banking payment system where real-time up-to-date information is critical.
BENNEJMA ElyesPosted Apr 11, 2017, 9:04 AM
When i try to add a customer i get this error :"Bad Request - Invalid URL"someone can help me please .. thank you
vara reddyPosted Mar 20, 2017, 3:10 AM
Nice article. Here is another one using Asp.Net Core 1.1 with EntityframeworkCore and client side validations. http://reddyinfosoft.blogspot.in/2017/03/starting-with-aspnet-core-using-visual_20.html
irish labianoPosted Jan 18, 2017, 7:29 AM
Saves my life. what if i need to display the ValidationSummary? tnx
Sandeep Singh ShekhawatPosted Nov 21, 2016, 10:54 AM
Glad to know that you find it helpful. Thanks for lovely comments ??
Aleena SaviourPosted Oct 29, 2016, 9:35 AM
Good
Prasanna MuraliPosted Oct 22, 2016, 11:49 AM
Nice post
RajaPosted Oct 21, 2016, 8:35 AM
Nice Share...
Manav PandyaPosted Oct 20, 2016, 12:36 PM
Nice share sir ...
Chandradev PrasadPosted Oct 20, 2016, 4:56 AM
Nice example.