Simple Scaffolding CRUD Operations in ASP.NET Core Using EF Core DB First Approach

Introduction

 
In this article, we will perform simple scaffold CRUD operations in ASP.NET Core using the EF Core Database First Approach. Creating a model from an existing database is known as the Database First Approach. Scaffolding is a technique used to generate views and controllers based on the model present in the application. Using scaffolding, you can save your time by creating CRUD operations automatically from your model. We have to perform the following steps to achieve the desired goal.
  1. Create SQL Table
  2. Create ASP.NET Core Web Application Project
  3. Install Required Packages
  4. Create Model from Existing Database
  5. Add Controller
  6. Test and run the application

Create SQL Table

 
Create a database named TestDB in SQL Server Management Studio and then create a table named EmployeeMaster in it which will have three columns EmployeeID, EmployeeFirstName, and EmployeeLastName. Here is a table query:
  1. CREATE TABLE EmployeeMaster (  
  2.     EmployeeID INT   NOT NULL  IDENTITY    PRIMARY KEY,  
  3.     EmployeeFirstName varchar(255) NOT NULL,  
  4.     EmployeeLastName  varchar(255) NOT NULL  
  5. );  

Create ASP.NET Core Web Application Project

 
Now we will create an ASP.NET Core Web Application project.
 
Step 1
Simple Scaffolding CRUD Operations In ASP.NET Core Using EF Core DB First Approach
 
Step 2
 
Simple Scaffolding CRUD Operations In ASP.NET Core Using EF Core DB First Approach
 
Step 3
 
Simple Scaffolding CRUD Operations In ASP.NET Core Using EF Core DB First Approach
 
Step 4
Simple Scaffolding CRUD Operations In ASP.NET Core Using EF Core DB First Approach
 

Install Required Nuget Packages

 
Select Tools menu, select NuGet Package Manager > Package Manager Console.
 
 
 
Install SQL Server provider by running the following command in the Package Manager Console.
  1. Install-Package Microsoft.EntityFrameworkCore.SqlServer  
To add Entity Framework Core Tool, run the following command,
  1. Install-Package Microsoft.EntityFrameworkCore.Tools  

Create Model from Existing Database

 
We will use the following Scaffold-DbContext command to create a model from our existing database
  1. Scaffold-DbContext "Server=DESKTOP-GV4424J;Database=TestDB;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models 
In the above command, the first parameter is connection string, the second parameter is provider name and third parameter –OutputDir is used to determine where our all classes will be generated. After running the command EmployeeMaster class and TestDBContext class (by deriving DbContext) from our TestDB will be created under the Models folder.
 

Add Controller

 
Right-click on the controller. Add->Controller. Select the MVC Controller with the views, using the entity framework.
 
Simple Scaffolding CRUD Operations In ASP.NET Core Using EF Core DB First Approach
 
Select EmployeeMaster class as a model class, TestDBContext as Data context class and Name Controller as EmployeeController as shown below. 
 
Simple Scaffolding CRUD Operations In ASP.NET Core Using EF Core DB First Approach
 
After creating a controller, all CRUD operations for the controller will be automatically generated.
  1. public class EmployeeController : Controller  
  2. {  
  3.         private readonly TestDBContext _context;  
  4.   
  5.         public EmployeeController(TestDBContext context)  
  6.         {  
  7.             _context = context;  
  8.         }  
  9.   
  10.         // GET: Employee  
  11.         public async Task<IActionResult> Index()  
  12.         {  
  13.             return View(await _context.EmployeeMaster.ToListAsync());  
  14.         }  
  15.   
  16.         // GET: Employee/Details/5  
  17.         public async Task<IActionResult> Details(int? id)  
  18.         {  
  19.             if (id == null)  
  20.             {  
  21.                 return NotFound();  
  22.             }  
  23.   
  24.             var employeeMaster = await _context.EmployeeMaster  
  25.                 .FirstOrDefaultAsync(m => m.EmployeeId == id);  
  26.             if (employeeMaster == null)  
  27.             {  
  28.                 return NotFound();  
  29.             }  
  30.   
  31.             return View(employeeMaster);  
  32.         }  
  33.   
  34.         // GET: Employee/Create  
  35.         public IActionResult Create()  
  36.         {  
  37.             return View();  
  38.         }  
  39.   
  40.         // POST: Employee/Create  
  41.         // To protect from overposting attacks, please enable the specific properties you want to bind to, for   
  42.         // more details see http://go.microsoft.com/fwlink/?LinkId=317598.  
  43.         [HttpPost]  
  44.         [ValidateAntiForgeryToken]  
  45.         public async Task<IActionResult> Create([Bind("EmployeeId,EmployeeFirstName,EmployeeLastName")] EmployeeMaster employeeMaster)  
  46.         {  
  47.             if (ModelState.IsValid)  
  48.             {  
  49.                 _context.Add(employeeMaster);  
  50.                 await _context.SaveChangesAsync();  
  51.                 return RedirectToAction(nameof(Index));  
  52.             }  
  53.             return View(employeeMaster);  
  54.         }  
  55.   
  56.         // GET: Employee/Edit/5  
  57.         public async Task<IActionResult> Edit(int? id)  
  58.         {  
  59.             if (id == null)  
  60.             {  
  61.                 return NotFound();  
  62.             }  
  63.   
  64.             var employeeMaster = await _context.EmployeeMaster.FindAsync(id);  
  65.             if (employeeMaster == null)  
  66.             {  
  67.                 return NotFound();  
  68.             }  
  69.             return View(employeeMaster);  
  70.         }  
  71.   
  72.         // POST: Employee/Edit/5  
  73.         // To protect from overposting attacks, please enable the specific properties you want to bind to, for   
  74.         // more details see http://go.microsoft.com/fwlink/?LinkId=317598.  
  75.         [HttpPost]  
  76.         [ValidateAntiForgeryToken]  
  77.         public async Task<IActionResult> Edit(int id, [Bind("EmployeeId,EmployeeFirstName,EmployeeLastName")] EmployeeMaster employeeMaster)  
  78.         {  
  79.             if (id != employeeMaster.EmployeeId)  
  80.             {  
  81.                 return NotFound();  
  82.             }  
  83.   
  84.             if (ModelState.IsValid)  
  85.             {  
  86.                 try  
  87.                 {  
  88.                     _context.Update(employeeMaster);  
  89.                     await _context.SaveChangesAsync();  
  90.                 }  
  91.                 catch (DbUpdateConcurrencyException)  
  92.                 {  
  93.                     if (!EmployeeMasterExists(employeeMaster.EmployeeId))  
  94.                     {  
  95.                         return NotFound();  
  96.                     }  
  97.                     else  
  98.                     {  
  99.                         throw;  
  100.                     }  
  101.                 }  
  102.                 return RedirectToAction(nameof(Index));  
  103.             }  
  104.             return View(employeeMaster);  
  105.         }  
  106.   
  107.         // GET: Employee/Delete/5  
  108.         public async Task<IActionResult> Delete(int? id)  
  109.         {  
  110.             if (id == null)  
  111.             {  
  112.                 return NotFound();  
  113.             }  
  114.   
  115.             var employeeMaster = await _context.EmployeeMaster  
  116.                 .FirstOrDefaultAsync(m => m.EmployeeId == id);  
  117.             if (employeeMaster == null)  
  118.             {  
  119.                 return NotFound();  
  120.             }  
  121.   
  122.             return View(employeeMaster);  
  123.         }  
  124.   
  125.         // POST: Employee/Delete/5  
  126.         [HttpPost, ActionName("Delete")]  
  127.         [ValidateAntiForgeryToken]  
  128.         public async Task<IActionResult> DeleteConfirmed(int id)  
  129.         {  
  130.             var employeeMaster = await _context.EmployeeMaster.FindAsync(id);  
  131.             _context.EmployeeMaster.Remove(employeeMaster);  
  132.             await _context.SaveChangesAsync();  
  133.             return RedirectToAction(nameof(Index));  
  134.         }  
  135.   
  136.         private bool EmployeeMasterExists(int id)  
  137.         {  
  138.             return _context.EmployeeMaster.Any(e => e.EmployeeId == id);  
  139.         }  

Run the application

 
Before running the application open TestDBContext class and comment on the following code present in the OnConfiguring method.
  1.   protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)  
  2.         {  
  3.             if (!optionsBuilder.IsConfigured)  
  4.             {  
  5.   
  6. //#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.  
  7. //                optionsBuilder.UseSqlServer("Server=DESKTOP-GV4424J;Database=TestDB;Trusted_Connection=True;");  
  8.               
  9.             }  
  10.   
  11.         }  
Add the following code in the ConfigureServices method in Startup class and then run the application.
  1. public void ConfigureServices(IServiceCollection services)  
  2.         {  
  3.             services.AddControllersWithViews();  
  4.   
  5.             services.AddDbContext<TestDBContext>(options => options.UseSqlServer("Server=DESKTOP-GV4424J;Database=TestDB;Trusted_Connection=True;"));  
  6.   
  7.         }  
Create
 
Simple Scaffolding CRUD Operations In ASP.NET Core Using EF Core DB First Approach
 
Update
 
Simple Scaffolding CRUD Operations In ASP.NET Core Using EF Core DB First Approach
 
Read
 
Simple Scaffolding CRUD Operations In ASP.NET Core Using EF Core DB First Approach
 
Delete
 
Simple Scaffolding CRUD Operations In ASP.NET Core Using EF Core DB First Approach
 

Conclusion

 
In this post, we have seen how to perform scaffolding in ASP.NET Core using EF Core. Hope you all liked it!
 
Thanks for reading!


Similar Articles