Introduction
We will learn CRUD (Create, Read, Update, and Delete) operations in ASP.NET Core MVC (.Net 6.0). We will use Entity Framework Core 6 to interact with the SQL Server database. We will use two Entity for CRUD operation.
Cover the following points in this blog.
- Create ASP.NET Core MVC 6.0 project in visual studio 2022
- Install all the necessary packages from NuGet.
- Create entities in the Model folder.
- Crete ApplicationDbContext class to interact with Database
- Add connection string of SQL Server database into appsettings.json file
- Run migration commands inside Package Manager Console (PMC)
- Add-Migration "Initial"
- Update-Database
- Add controllers inside the controller folder
- Add view models
- Add Views
- Add Validation
Prerequisites
- Visual Studio 2022 (.Net 6.0)
- SQL Server
Step 1. Create ASP.NET Core MVC 6 project
First, open Visual Studio 2022 and click on "Create a New Project" (highlighted in yellow color)
Search "MVC" in the Search box (Search for templates (Alt+s)) and select ASP.NET Core Web App (Model-View-Controller) as a project template and click the Next button.
Enter a project name and click next.
Go with the basic configuration as per the below screen; click Next.
ASP.NET Core MVC (.Net 6.0) project structure
Step 2. Install the required package from NuGet
Required package for ASP.NET Core MVC (.Net 6.0) CRUD operation application
- Microsoft.EntityFrameworkCore
- Microsoft.EntityFrameworkCore.SqlServer
- Microsoft.EntityFrameworkCore.Tools
Now, we install the above package one by one. Right-click on Dependencies and select "Manage NuGet Packages…"
Install Microsoft.EntityFrameworkCore package.
Install Microsoft.EntityFrameworkCore.SqlServer package.
Install Microsoft.EntityFrameworkCore.Tools package.
All install packages are showing in Dependencies -> Packages
Step 3. Add Category and Product entities class into the Model folder
Step 4. Add ApplicationDbContext class inside the Data folder
Step 5. Add connectionstring into appsettings.json
"ConnectionStrings": {
"MVC6CrudConnetionString": "Data Source=DESKTOP-LOPK1F2;Integrated Security=true;Initial Catalog=MVC6CrudDb;TrustServerCertificate=True;MultipleActiveResultSets=true;"
}
Step 6. Add DbContext Service into Program.cs file with the connection string
Build solution
Step 7. Run migration commands inside Package Manager Console (PMC) to create a Database
Package Manager Console (PMC)
Add-Migration "Initial" command
Update-Database command
MVC6CrudDb created into SQL Server with Categories and Products table.
Step 8. Add the Category controller and Product controller in the controller folder
In the same way, we added a Product controller, and now both are showing in the controller folder.
Category CRUD operation screens
Product CRUD operation screens