In this article, we will learn CRUD Operations in ASP.NET Core 5.0. We will use Entity Framework Core 5.0 to interact with sql-server database and for performing CRUD operations.
Before moving ahead, i am going to give you a brief introduction to .NET 5.0
What is .NET 5.0 ?
The .NET 5.0 is the major release of .NET Core after .Net Core 3.1. We can say that .NET 5 = .NET Core vNext. In .NET 5 lot of new .NET APIs, runtime capabilities and language features has been added.
The main reason behind presenting .NET 5 is to produce a single .NET runtime and framework that can be used everywhere and that has uniform runtime behaviors.
But the question is why .NET 5.0, why not .NET Core 4.0 ?
There are two main reasons:
- Microsoft skipped version numbers 4.x to avoid confusion with .NET Framework 4.x.
- Microsoft dropped the word "Core" from the name to emphasize that this is the main implementation of .NET going forward.
To Avoid Confusion:
- ASP.NET Core 5.0 is based on .NET 5.0 but retains the name "Core" to avoid confusing it with ASP.NET MVC 5.
- Entity Framework Core 5.0 retains the name "Core" to avoid confusing it with Entity Framework 5.
So we can say that, there is no .NET Core 5.0, now everything falls under one umbrella, which is .NET 5.
The whole idea is to bring all .NET runtimes into a single .NET platform with unified base class libraries (BCL) for all kinds of applications like ASP.NET Core, Windows Forms, WPF, Blazor etc.
I Will Cover The Following Points In This Article:
- Basic prerequisites to run .Net core 5.0 project.
- How to create ASP.NET CORE 5.0 project in visual studio.
- ASP.NET CORE 5.0 project structure.
- How to install all the necessory packages from Nuget.
- Create Database and required tables for CRUD operation.
- Create model and context class from an existing database.
- Create Employee controller.
- Miscellaneous Configuration to run ASP.NET CORE 5.0 project.
- Implement ASP.NET Core MVC CRUD Operations.
- Validations in ASP.NET Core MVC.
- Run the application.
- Instructions to download and run the project.
- Summary.
Step 1 - Prerequisites
Visual Studio 2019 latest version(at least 16.6.0).
.NET SDK 5.0 or later.
Sql-Server 2017 or later version.
Note
In case your visual studio version is lower then mentioned above, you can upgrade using visual studio installer.
You will have the option to update in case it is not up to date.
Step 2 - Create ASP.NET Core 5.0 Project.
Open Visual Studio and click on "Create a new project".
Select the ASP.NET Core Web App(Model-View-Controller) as a project template and click Next.
Enter the Project name and click Next.
In additional information, select the fields as configured below and click on Create.
Step 3 - ASP.NET CORE 5.0 Project Structure
- Dependencies: It contains all the installed NuGet packages. We can manage the NuGet packages by right clicking on it.
- Properties: It contains launchSettings.json file which has visual studio profiles, iis and debug setting.
- wwwroot folder: It is the web root folder of asp.net core application where we can put all the static files such as javascript , css , images.
- Controllers: It contails all the controller class we create in our asp.net core mvc application.
- Models: We can put all the model or view model classes inside this folder.
- Views: We can add views for certain actions methods inside view folder. There will be seperate folder for each view we create inside Views folder.
- appsettings.json: It is the application configuration file which is used to store configuration settings i.e connections strings of the database, global variables etc.
- Program.cs : Initially asp.net core application starts as a console application. In the Main method it calls the CreateWebHostBuilder() method that configures the asp.net core setting and launch it as asp.net core application.
- Startup.cs: It contains the ConfigureServices() and Configure methods. As the name implies ConfigureServices() method configures all the services which are going to used by the application. Configure method take care of all the request processing pipelines.
Step 4 - Install All Necessary Packages From NuGet
Right-click on Dependencies and then Manage NuGet Package.
In order to access the MS SQL Server database, we need to install the below provider. Search “Microsoft.EntityFrameworkCore.SqlServer” as below and install.
To execute EF Core commands we will require EF-Core tools. Search “Microsoft.EntityFrameworkCore.Tools” as below and install.
This package will allow us to execute scaffold , migration commands from package manager console (PMC). It will also help you to create database context and the model classes.
Step 5 - Create Database And Employee Table
Create a new database named CompanyDB in sql-server and execute the below SQL query to create employee table.
Step 6 - Create Model And Context Class From An Existing Database.
Creating model and context class from an existing database is also called Database-First approach. So to reverse engineer we need to execute Scaffold-DbContext command. This scaffold command will create models and context classes based on the database schema.
Run the below scaffold command after replacing server name, database name with your applications connection setting.
Above scaffold, commands have three parameters.
First parameter of the scaffold command have server name, database name and integrated security information.
Second parameter have information about provider. we are using sql-server so provider will be Microsoft.EntityFrameworkCore.SqlServer.
Third parameter i.e -OutputDir is use to specify the location where we want to generate model classes. In our cases it is Models folder.
Step 7 - Create Employee Controller
On the controller folder, Right-click and then Add > Controller. Select the controller template as highlighted below and Click Add. In the dialog, provided next type name of the controller, in our case it is EmployeeController.cs and click Add to create EmployeeController class under controller folder.
Finally the employee controller class has been created with basic auto generated code for crud operation.
Step 8 - Miscellaneous Configuration
Store connection string inside appsettings.json and remove auto generated OnConfiguring() method from dbcontext class as it is not good practice to have connection string inside OnConfiguring() method.
In the Startup.cs class add CompanyDBContext as a service inside ConfigureService() method as below. We will retrieve the connection string value from appsettings.json file through IConfiguration object's GetConnectionString() method.
In order load Employee Controller's Index view on application start, we simply need to change controller name to Employee inside Configure() method.
Inject CompnyDBContext object in the Employees controller's constructor using dependency injection.
Step 9 - ASP.NET Core MVC CRUD Operations
General Instructions To Add Views,
Under Views folder, Create a new folder named Employee. Click on the Employee folder and click Add.
Then Click on View and click on the Razor View – Empty template and then click on Add to create the view.
After adding all the views for CRUD operation, the Employee folder will have the following views file.
Index Action Method
Replace your Index action method with the below code inside the employee controller.
Replace auto generated Index View code with below code,
Index
It returns all the employees from employee table and presents it to the index view.
AddOrEdit Action Method
Replace Create and Edit action methods with AddOrEdit single action method below,
Replace below code in AddOrEdit view,
Create
It takes employee details as input and creates a new employee record in the employee table.
Edit
It takes employee details as input and updates the new details in the employee table.
Details Action Method
Replace Details action method code with below code snippet.
Replace below code in Details view,
Details
It returns the employee details from the employee table by employee ID.
Delete Action Method
Replace Delete action method code with the below code snippet.
Replace below code in Delete view:
Delete: it takes the employee ID as input, and after confirm delete popup, deletes the employee from employee table.
Step 10 - Validations In ASP.NET Core
We need to check whether the provided input is correct or not before submitting the data. We perform Client side as well as Server side validation for this purpose.
Model Validation
To perform model validation, we need to use vaidation attributes presents in the System.ComponentModel.DataAnnotations namespace. These attributes decides the validation rules for the model properties.
Below are the few importent built-in model attributes,
- [Required] - its validates that the input field should not be null or empty.
- [Compare] - it validate that the two model fields match or not.
- [Range] - it validate that the provided input is in the specified range or not.
- [StringLength] - it validate that the provided string input should not exceed the specified limit.
- [ValidateNever] - if any model property is decorated with VlaidateNever attribues, it mean this property is excluded from validation.
In our crud operation, we have created EmployeeValidator class with properties that need to perform model validation. In the name property we set Required and MaxLenghth attribute to validate against for condition, means name should not be empty and it should not exceed maxlength specified.
Server Side Validation
Server side validation performs using ModelState property of ControllerBase class. Generally ModelState handle errors that comes from model binding and model validation. At the execution od the controller action, ModelState.IsValid checks whether any error present or not. If it is true then it will allow to proceed otherwise return the view.
Client Side Validation
Client side validation will not allow the page to submit until the form is valid. It prevent the unnecessary round trip to server.
The below script references support client side validation:
In Layout.cshtml
In _ValidationScriptsPartial.cshtml
Step 11 - Run The Application
When we Run the application. By default index view will be loaded.
Click on Create New button to create new employee.
Click on Edit button to Edit an employee.
Click on Details button to see the employee detail.
Click on Delete button to delete the employee.
In order to download and run the application, please follow the below steps,
Step 1
Download the solution files from the attachement of this article.
Step 2
Open the solution file in Visual Studio 2019 or later.
Step 3
In order to restore the required NuGet packages, rebuild the solution.
Step 4
Change the connection string in the appsettings.json file with your SQL Server connection string.
Step 5
Run the application.
No comments:
Post a Comment