Asp.Net Core MVC CRUD with EF Core - CodAffection
[the_ad_placement id="before-content"]

Asp.Net Core MVC CRUD with EF Core

Asp.Net Core MVC CRUD Operations with EF Core.

Create, Retrieve, Update, and Delete [CRUD] are the basic operations in any application. Applications without any of these operations would be rare. With this article, we will implement CRUD Operations in ASP.NET Core MVC application with Entity Framework Core – Code First Approach. To demonstrate the topic we will build an application for storing and managing employee details.

GitHub repository for the demo project:

Create ASP.NET Core MVC Project

From Visual Studio, Go to File > New > Project( Ctrl + Shift + N). Then select ASP.NET Core Web Application.

In template wizard, Select Web Application(MVC) template. Make sure to select the latest ASP.NET Core Version from top dropdown. Uncheck HTTPS option, which is not required in the development environment.

Setup Database for EF Core

The database for the project will be created and managed through EF Core – Code First Approach. So first of all, we have to install corresponding NuGet Packages. Right-click on the project from solution explorer, select Manage NuGet Packages. From browse tab, search and install Microsoft.EntityFrameworkCore and its dependent packages.

Showing list of NuGet Packages for Entity Framework Core

Now let’s define a model class for employee entity in Models folder as Employee.

In Entity Framework, the actual physical entities in a database are created and managed from DBContext class. In our application, EmployeeContext class does the job. To create a table corresponding to the employee model class, We’ve added Employees property of the type DbSet.

Inject DbContext Class with Dependency Injection.

In order to interact with database, we need an instance of the DbContext class. We can do that with dependency injection. For the class constructor parameter options, following informations are required.

  • Database Provider – whether it is SQL Server or MySQL or PostgreSQL etc.
  • DB Connection String

First of all, we will save the connection string in appsettings.json file as follows.

Now let’s create the DbContext instance by passing both DB connection string and DB provider using dependency injection from Asp.Net Core. For that, we just need to update ConfigureServices method from Startup class. Invoke AddDbConext method from services collection as follows.

How and when this dependency injection works? we’ll discuss that later, once we add an employee controller in this project.

Initiate DB Migration

So far we have been modeling our Database, Let’s create the actual DB. First of all open Package Manager Console.for that you can right-click the project from Solution Explorer then go to Tools > NuGet Package Manager > Package Manager Console. Inside the console execute the following commands one by one.

Add-Migration "InitialCreate"

Now you should have the EmployeeDB(mentioned in connection string) created as per our employee model.

Create MVC Controller For CRUD Operations

Let’s create a new MVC controller EmployeeController. Go to Controller > Add > Controller, then select ‘MVC Controller with views, using Entity Framework’ template. Select Employee and EmployeeContext as Model and DbContext class respectively.

The created MVC controller will have all the action methods for all CRUD operations, even though I would like to simplify it as follows. Each of the action methods will be discussed later in this article.

Now a few words on ASP.NET Core dependency injection: As you know, an instance of MVC controller will be created once a request is made into it. But there is a constructor parameter context of the type EmployeeContext. How can we pass value for the parameter when the controller instance is created by the ASP.NET Core framework itself? There comes the importance of dependency injection, that we configured above in Startup class, whenever a controller constructor needs an instance of DbContext, the dependency injection passes an instance. So the rest of the action methods inside the controller can interact with the Database through the injected DbContext instance.

Retrieve List of Records in an MVC View

Purpose of each action methods in EmployeeController.

  • Index: Retrieve list of records from the employees table.
  • AddOrEdit: Handle both insert and update operation.
  • Delete: Remove an employee record with a given employee id.

All of the above action methods either manipulate the data or retrieve existing data from the database. Now we’ve to design the user interface with razor views for showing retrieved data or a form/ button to submit data to action methods. You could see such razor views in /Views/Employee folder.

Now let’s retrieve the list of employees using Index action method.

List of records from employees table can easily be retrieved with DbSet property Employees as shown above. The collection of records is returned with the function View. So there should be a razor view file index.cshtml (same name as that of index action method) to render the collection of records. We’ve done that with help of an HTML table using a foreach loop.

New employee can be inserted with + button from last column header. The last column contains button for edit/ update and delete operation. Now the index view should look like this.

Did you see the navbar here? inside our razor view, we only said to show the HTML table, now where is this navbar coming from? It’s from our global layout view Shared/_Layout.cshtml. Not only the navbar, the entire HTML declaration and surrounding body and head tag are defined inside this layout view. It will thereby default in any MVC project to enclose all of the views file. Stylesheet reference for Bootstrap and Font Awesome should be added to it. Most of the case Bootstrap will be there already, just add the Font Awesome stylesheet reference.

Add or Edit a Record

Normally by default there will be separate methods for insert and update operation. here in this project we’ve combined them into one. First of all, let’s define GET and POST methods for both insert and update operation with AddOrEdit action method.

And here is our AddOrEdit.cshtml view for the above GET action method.

This view is returned from AddOrEdit action method of the type GET. The method returns a fresh instance of the employee model, if the id parameter is 0. Else corresponding employee record with given id is returned. Finally, the returned model is populated inside AdddOrEdit.cshtml view. For an insert operation the form looks like this.

This formwill submited to AddOrEdit Post action method. We’ve handled both operations within if-else block based on the value of id parameter. We just need to call Add or Update method from DbContext object, for insert and update operation respectively. After all, invoke the Entity Framework method SaveChangesAsync. If the operation is successful we’ll be redirected to Index action method to return the list of records with the latest modification.

Form Validation

Inside our Employee model, we defined FullName property with Required attribute, Which is means the property should contain a value before submitting the above form. Entity Framework Core Validation support many attributes like this. We’ve checked the validation status of the model within GET action method AddOrEdit with ModelState.IsValid property.

If there is any validation error, the same form is returned with the same model updated with validation error message.

Delete a Record

You could delete a record with delete button from index view, it will handle in Delete action method.

Inside the method, FindAsync retrieves the corresponding record with the given id into employee variable, Finally invoke Remove method from Employees DbSet property. and don’t forget to call SaveChangesAsync method which executes respective SQL Commands in back-end SQL Server Engine.

End of this discussion, The following discussion might help you to add more features in this application.

Video Tutorial on this Topic

Make sure to subscribe our YouTube Channel – CodAffection.

9 thoughts on “Asp.Net Core MVC CRUD with EF Core”

  1. You need .NET Core 2.2. for this. Just install it using Visual Studio installer > Modify > Individual Components > .NET Core 2.2

  2. Thank you for this wonderful tutorials Shamseer, Would it be possible to create CRUD Select statement in core razor pages WITHOUT ENTITY FRAMEWORK please?! that would be really helpful sir, Thanks

  3. excelente tutoríal me a servido mucho
    Si es posible algún ejemplo utilizando Storage Procedure con EF con una DB relacional SQL Server

    le agradezco de antemano

  4. Hello Sir,
    I like your channel, every day I check your channel if any video comes in.

    Sir, Please create a tutorial video for authentication & login with social login. Use(Facebook & Google) social login with Angular 7 & ASP.Net core.
    Please share this one.


Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top
Share via
Copy link
Powered by Social Snap