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. public EmployeeController(TestDBContext context)
  5. {
  6. _context = context;
  7. }
  8. // GET: Employee
  9. public async Task<IActionResult> Index()
  10. {
  11. return View(await _context.EmployeeMaster.ToListAsync());
  12. }
  13. // GET: Employee/Details/5
  14. public async Task<IActionResult> Details(int? id)
  15. {
  16. if (id == null)
  17. {
  18. return NotFound();
  19. }
  20. var employeeMaster = await _context.EmployeeMaster
  21. .FirstOrDefaultAsync(m => m.EmployeeId == id);
  22. if (employeeMaster == null)
  23. {
  24. return NotFound();
  25. }
  26. return View(employeeMaster);
  27. }
  28. // GET: Employee/Create
  29. public IActionResult Create()
  30. {
  31. return View();
  32. }
  33. // POST: Employee/Create
  34. // To protect from overposting attacks, please enable the specific properties you want to bind to, for
  35. // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
  36. [HttpPost]
  37. [ValidateAntiForgeryToken]
  38. public async Task<IActionResult> Create([Bind("EmployeeId,EmployeeFirstName,EmployeeLastName")] EmployeeMaster employeeMaster)
  39. {
  40. if (ModelState.IsValid)
  41. {
  42. _context.Add(employeeMaster);
  43. await _context.SaveChangesAsync();
  44. return RedirectToAction(nameof(Index));
  45. }
  46. return View(employeeMaster);
  47. }
  48. // GET: Employee/Edit/5
  49. public async Task<IActionResult> Edit(int? id)
  50. {
  51. if (id == null)
  52. {
  53. return NotFound();
  54. }
  55. var employeeMaster = await _context.EmployeeMaster.FindAsync(id);
  56. if (employeeMaster == null)
  57. {
  58. return NotFound();
  59. }
  60. return View(employeeMaster);
  61. }
  62. // POST: Employee/Edit/5
  63. // To protect from overposting attacks, please enable the specific properties you want to bind to, for
  64. // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
  65. [HttpPost]
  66. [ValidateAntiForgeryToken]
  67. public async Task<IActionResult> Edit(int id, [Bind("EmployeeId,EmployeeFirstName,EmployeeLastName")] EmployeeMaster employeeMaster)
  68. {
  69. if (id != employeeMaster.EmployeeId)
  70. {
  71. return NotFound();
  72. }
  73. if (ModelState.IsValid)
  74. {
  75. try
  76. {
  77. _context.Update(employeeMaster);
  78. await _context.SaveChangesAsync();
  79. }
  80. catch (DbUpdateConcurrencyException)
  81. {
  82. if (!EmployeeMasterExists(employeeMaster.EmployeeId))
  83. {
  84. return NotFound();
  85. }
  86. else
  87. {
  88. throw;
  89. }
  90. }
  91. return RedirectToAction(nameof(Index));
  92. }
  93. return View(employeeMaster);
  94. }
  95. // GET: Employee/Delete/5
  96. public async Task<IActionResult> Delete(int? id)
  97. {
  98. if (id == null)
  99. {
  100. return NotFound();
  101. }
  102. var employeeMaster = await _context.EmployeeMaster
  103. .FirstOrDefaultAsync(m => m.EmployeeId == id);
  104. if (employeeMaster == null)
  105. {
  106. return NotFound();
  107. }
  108. return View(employeeMaster);
  109. }
  110. // POST: Employee/Delete/5
  111. [HttpPost, ActionName("Delete")]
  112. [ValidateAntiForgeryToken]
  113. public async Task<IActionResult> DeleteConfirmed(int id)
  114. {
  115. var employeeMaster = await _context.EmployeeMaster.FindAsync(id);
  116. _context.EmployeeMaster.Remove(employeeMaster);
  117. await _context.SaveChangesAsync();
  118. return RedirectToAction(nameof(Index));
  119. }
  120. private bool EmployeeMasterExists(int id)
  121. {
  122. return _context.EmployeeMaster.Any(e => e.EmployeeId == id);
  123. }

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. //#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.
  6. // optionsBuilder.UseSqlServer("Server=DESKTOP-GV4424J;Database=TestDB;Trusted_Connection=True;");
  7. }
  8. }
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. services.AddDbContext<TestDBContext>(options => options.UseSqlServer("Server=DESKTOP-GV4424J;Database=TestDB;Trusted_Connection=True;"));
  5. }
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!