Blazor Server App CRUD With Entity Framework Core In .Net 5

Introduction

 
In this article, we will learn what Blazor is and how we can set up Blazor by making a basic CRUD Application with Entity Framework Core Code first approach in .Net 5 (the latest version).
 
Prerequisites
  • Install the latest .NET Core 3.1 SDK from here.
  • Install the latest version of Visual Studio 2019 from here.
What we are going to cover in this?
  • What is Blazor and why it is exciting for C# Developers?
  • Difference between Blazor Server - Blazor Web Assembly
  • Setup the CRUD App using Blazor
  • Run and Test 
Download Source Code - Git Hub
 

What is Blazor and why is it exciting for C# Developers?

 
Blazor is a .NET web system that runs in the program. Think Angular or React however controlled by C# and Razor. Designers make Blazor applications utilizing a combination of C#, Razor, and HTML. These applications execute .NET congregations utilizing the Mono .NET runtime carried out through WebAssembly. Blazor utilizes the most recent web guidelines and requires no extra modules or additional items to run, this is not another Silverlight.
 

Blazor Server App

 
In the worker side facilitating model (Blazor Server-Side), Blazor is executed on the worker from inside an ASP.NET Core application. UI refreshes, occasion dealing with, and JavaScript brings are taken care of over a SignalR association.
 
Blazor also supports features of the SPA(Single Page Application)  framework such as,
  • Routing
  • Layouts
  • Forms and validation
  • JavaScript interop
  • Build on save during development
  • Server-side rendering
  • Dependency Injection
Blazor Server App CRUD With Entity Framework Core In .Net 5

Blazor Web Assembly 

 
In the customer-side model (Blazor WebAssembly), the Blazor application, its conditions, and the .NET runtime are downloaded to the program, and the application is executed straightforwardly on the program UI string. All UI updates and occasions taking care of occur inside a similar cycle.
Blazor Server App CRUD With Entity Framework Core In .Net 5

Setup

 
Create a Blazor Server App.
 
Blazor Server App CRUD With Entity Framework Core In .Net 5 
 
Add the project name for your Application
 
Blazor Server App CRUD With Entity Framework Core In .Net 5 
 
Make sure you have .Net 5.0 installed in your machine and then it will automatically be added in the dropdown select target framework as .Net 5.0
 
Blazor Server App CRUD With Entity Framework Core In .Net 5 
 
A basic scaffolded template will generate here is the project structure
 
Blazor Server App CRUD With Entity Framework Core In .Net 5
 
 Create an class in the Data folder to act as table in database to store all our CRUD Operations.
 
Employee.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations;  
  4. using System.Linq;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace BlazorCRUD.Data  
  8. {  
  9.     public class Employee  
  10.     {  
  11.         [Key]  
  12.         public int Id { getset; }  
  13.         public string EmployeName { getset; }  
  14.         public string Gender { getset; }  
  15.         public string City { getset; }  
  16.         public string Designation { getset; }  
  17.     }  
  18. }  
 Create a dbcontext file to setup the configuration with Database.
 
AppDbContext.cs
  1. using Microsoft.EntityFrameworkCore;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace BlazorCRUD.Data  
  8. {  
  9.     public class AppDBContext : DbContext  
  10.     {  
  11.         public AppDBContext(DbContextOptions<AppDBContext> options) : base(options)  
  12.         {  
  13.   
  14.         }  
  15.         public DbSet<Employee> Employees { getset; }  
  16.     }  
  17. }  
Create an employee service with all the business logic inside this service. 
 
Setup a connection string in appsettings.json file.
 
appsettings.json 
  1. {  
  2.   "Logging": {  
  3.     "LogLevel": {  
  4.       "Default""Information",  
  5.       "Microsoft""Warning",  
  6.       "Microsoft.Hosting.Lifetime""Information"  
  7.     }  
  8.   },  
  9.   "AllowedHosts""*",  
  10.   "ConnectionStrings": {  
  11.     "myconn""server= Your Server name; database=BlazorCRUD;Trusted_Connection=True;"  
  12.   }  
  13. }  
 
EmployeeService.cs
 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using Microsoft.EntityFrameworkCore;  
  6.   
  7. namespace BlazorCRUD.Data  
  8. {  
  9.     public class EmployeeService  
  10.     {  
  11.         #region Property  
  12.         private readonly AppDBContext _appDBContext;  
  13.         #endregion  
  14.  
  15.         #region Constructor  
  16.         public EmployeeService(AppDBContext appDBContext)  
  17.         {  
  18.             _appDBContext = appDBContext;  
  19.         }  
  20.         #endregion  
  21.  
  22.         #region Get List of Employees  
  23.         public async Task<List<Employee>> GetAllEmployeesAsync()  
  24.         {  
  25.             return await _appDBContext.Employees.ToListAsync();  
  26.         }  
  27.         #endregion  
  28.  
  29.         #region Insert Employee  
  30.         public async Task<bool> InsertEmployeeAsync(Employee employee)  
  31.         {  
  32.             await _appDBContext.Employees.AddAsync(employee);  
  33.             await _appDBContext.SaveChangesAsync();  
  34.             return true;  
  35.         }  
  36.         #endregion  
  37.  
  38.         #region Get Employee by Id  
  39.         public async Task<Employee> GetEmployeeAsync(int Id)  
  40.         {  
  41.             Employee employee = await _appDBContext.Employees.FirstOrDefaultAsync(c => c.Id.Equals(Id));  
  42.             return employee;  
  43.         }  
  44.         #endregion  
  45.  
  46.         #region Update Employee  
  47.         public async Task<bool> UpdateEmployeeAsync(Employee employee)  
  48.         {  
  49.              _appDBContext.Employees.Update(employee);  
  50.             await _appDBContext.SaveChangesAsync();  
  51.             return true;  
  52.         }  
  53.         #endregion  
  54.  
  55.         #region DeleteEmployee  
  56.         public async Task<bool> DeleteEmployeeAsync(Employee employee)  
  57.         {  
  58.             _appDBContext.Remove(employee);  
  59.             await _appDBContext.SaveChangesAsync();  
  60.             return true;  
  61.         }  
  62.         #endregion  
  63.     }  
  64. }  
Configure the connection setup and inject the EmployeeService in Configure Services method in startup.cs file
 
Startup.cs
  1. public void ConfigureServices(IServiceCollection services)  
  2.         {  
  3.             services.AddRazorPages();  
  4.             services.AddServerSideBlazor();  
  5.             services.AddSingleton<WeatherForecastService>();  
  6.             services.AddScoped<EmployeeService>();  
  7.  
  8.             #region Connection String  
  9.             services.AddDbContext<AppDBContext>(item => item.UseSqlServer(Configuration.GetConnectionString("myconn")));  
  10.             #endregion  
  11.   
  12.         }  
Create the table by using these commands in Package Console Manager
 
Commands:
  • Add-Migration 'Your Migration Name'
  • Update-Databse 
 
Now the actual binding of Data will see once we create the Razor pages inside the Pages folder lets create pages and for each form. Will create the Employee Form where it will have the datatable to show all the Saved information in it.
 
To create a Razor component Right Click on pages ->  Click on Add -> Click on Razor Component then create a page with the Employee.Razor .
 
Employees.Razor
  1. @page "/Employees"  
  2. @using BlazorCRUD.Data  
  3. @inject EmployeeService employeeService  
  4.   
  5. <NavLink class="nav-link" href="AddEmployee">  
  6.     <span class="oi oi-plus" aria-hidden="true">Add New</span>  
  7.   
  8. </NavLink>  
  9.   
  10. <h1>Employee Info</h1>  
  11. @if (EmpObj is null)  
  12. {  
  13.     <p><em>Loading... !</em></p>  
  14. }  
  15. else  
  16. {  
  17.     <table class="table">  
  18.             <thead>  
  19.                 <tr>  
  20.                     <th>Emp Id</th>  
  21.                     <th>Employee Name</th>  
  22.                     <th>Gender</th>  
  23.                     <th>Designation</th>  
  24.                     <th>City</th>  
  25.                     <th>Action</th>  
  26.                 </tr>  
  27.             </thead>  
  28.         <tbody>  
  29.             @foreach(var emp in EmpObj)  
  30.                 {  
  31.             <tr>  
  32.                 <td>@emp.Id</td>  
  33.                 <td>@emp.EmployeName</td>  
  34.                 <td>@emp.Gender</td>  
  35.                 <td>@emp.Designation</td>  
  36.                 <td>@emp.City</td>  
  37.                 <td>  
  38.                     <a class="nav-link" href="EditEmployee/@emp.Id">  
  39.                         <span class="oi oi-pencil" aria-hidden="true">Edit</span>  
  40.                     </a>  
  41.                     <a class="nav-link" href="Delete/@emp.Id">  
  42.                         <span class="oi oi-trash" aria-hidden="true">Delete</span>  
  43.                     </a>  
  44.                 </td>  
  45.             </tr>  
  46.                 }  
  47.         </tbody>  
  48.     </table>  
  49. }  
  50.   
  51.   
  52. @code {  
  53.     List<Employee> EmpObj;  
  54.     protected override async Task OnInitializedAsync()  
  55.     {  
  56.         EmpObj = await Task.Run(() => employeeService.GetAllEmployeesAsync());  
  57.     }  
  58. }  
@page - the actual navigation page name 
 
@inject - Injection of Service layer here to have interaction with Business logic
 
@code - Where we call the service method to bind all the values inside the Razor component.
 
AddEmployee.cs
 
Injected the NavigateManager to navigate from one page to another with the page names.
  1. @page "/AddEmployee"  
  2. @using BlazorCRUD.Data  
  3. @inject EmployeeService employeeService  
  4. @inject NavigationManager NavigationManager  
  5.   
  6. <h2>Add Employee</h2>  
  7. <hr />  
  8.   
  9. <form>  
  10.     <div class="row">  
  11.         <div class="col-md-8">  
  12.             <div class="form-group">  
  13.                 <label for="Name" class="control-label">Name</label>  
  14.                 <input form="Name" class="form-control" @bind="@obj.EmployeName" />  
  15.             </div>  
  16.             <div class="form-group">  
  17.                 <label for="Gender" class="control-label"></label>  
  18.                 <select @bind="@obj.Gender" class="form-control">  
  19.                     <option value="">-Select Gender</option>  
  20.                     <option value="Male">Male</option>  
  21.                     <option value="Female">Female</option>  
  22.                 </select>  
  23.             </div>  
  24.             <div class="form-group">  
  25.                 <label for="Designation" class="control-label">Designation</label>  
  26.                 <input form="Designation" class="form-control" @bind="@obj.Designation" />  
  27.             </div>  
  28.             <div class="form-group">  
  29.                 <label for="City" class="control-label">City</label>  
  30.                 <input form="City" class="form-control" @bind="@obj.City" />  
  31.             </div>  
  32.   
  33.         </div>  
  34.     </div>  
  35.   
  36.     <div class="row">  
  37.         <div class="col-md-4">  
  38.             <div class="form-group">  
  39.                 <input type="button" class="btn btn-primary" @onclick="@CreateEmployee" value="Save"/>  
  40.                 <input type="button" class="btn btn-primary" @onclick="@Cancel" value="Cancel"/>  
  41.             </div>  
  42.         </div>  
  43.     </div>  
  44. </form>  
  45.   
  46. @code {  
  47.     Employee obj = new Employee();  
  48.     protected async void CreateEmployee()  
  49.     {  
  50.         await employeeService.InsertEmployeeAsync(obj);  
  51.         NavigationManager.NavigateTo("Employees");  
  52.     }  
  53.     void Cancel()  
  54.     {  
  55.         NavigationManager.NavigateTo("Employees");  
  56.     }  
  57. }  
 EditEmployee.razor
  1. @page "/EditEmployee/{Id}"  
  2. @using BlazorCRUD.Data  
  3. @inject EmployeeService employeeService  
  4. @inject NavigationManager NavigationManager  
  5.   
  6. <h2>Edit Employee</h2>  
  7. <hr />  
  8.   
  9. <form>  
  10.     <div class="row">  
  11.         <div class="col-md-8">  
  12.             <div class="form-group">  
  13.                 <input form="Name" class="form-control" @bind="@obj.Id" />  
  14.             </div>  
  15.             <div class="form-group">  
  16.                 <label for="Name" class="control-label">Name</label>  
  17.                 <input form="Name" class="form-control" @bind="@obj.EmployeName" />  
  18.             </div>  
  19.             <div class="form-group">  
  20.                 <label for="Gender" class="control-label"></label>  
  21.                 <select @bind="@obj.Gender" class="form-control">  
  22.                     <option value="">-Select Gender</option>  
  23.                     <option value="Male">Male</option>  
  24.                     <option value="Female">Female</option>  
  25.                 </select>  
  26.             </div>  
  27.             <div class="form-group">  
  28.                 <label for="Designation" class="control-label">Designation</label>  
  29.                 <input form="Designation" class="form-control" @bind="@obj.Designation" />  
  30.             </div>  
  31.             <div class="form-group">  
  32.                 <label for="City" class="control-label">City</label>  
  33.                 <input form="City" class="form-control" @bind="@obj.City" />  
  34.             </div>  
  35.   
  36.         </div>  
  37.     </div>  
  38.   
  39.     <div class="row">  
  40.         <div class="col-md-4">  
  41.             <div class="form-group">  
  42.                 <input type="button" class="btn btn-primary" @onclick="@UpdateEmployee" value="Update" />  
  43.                 <input type="button" class="btn btn-primary" @onclick="@Cancel" value="Cancel" />  
  44.             </div>  
  45.         </div>  
  46.     </div>  
  47. </form>  
  48.   
  49. @code {  
  50.     [Parameter]  
  51.     public string Id { getset; }  
  52.     Employee obj = new Employee();  
  53.     protected override async Task OnInitializedAsync()  
  54.     {  
  55.         obj = await Task.Run(() => employeeService.GetEmployeeAsync(Convert.ToInt32(Id)));  
  56.     }  
  57.     protected async void UpdateEmployee()  
  58.     {  
  59.         await employeeService.UpdateEmployeeAsync(obj);  
  60.         NavigationManager.NavigateTo("Employees");  
  61.     }  
  62.     void Cancel()  
  63.     {  
  64.         NavigationManager.NavigateTo("Employees");  
  65.     }  
  66. }  
 Actually we used to pass the the Id for Edit employee to fetch the details from the database and to store in edit employee form.
 
Delete.Razor
  1. @page "/Delete/{Id}"  
  2. @using BlazorCRUD.Data  
  3. @inject EmployeeService employeeService  
  4. @inject NavigationManager NavigationManager  
  5.   
  6. <h2>Delete Employee</h2>  
  7. <hr />  
  8. <h3>Are you sure want to delete this?</h3>  
  9. <form>  
  10.     <div class="row">  
  11.         <div class=" col-md-8">  
  12.             <div class="form-group">  
  13.                 <label>Employee Id:</label>  
  14.                 <label>@obj.Id</label>  
  15.             </div>  
  16.             <div class="form-group">  
  17.                 <label>Employee Name:</label>  
  18.                 <label>@obj.EmployeName</label>  
  19.             </div>  
  20.             <div class="form-group">  
  21.                 <label>Desigation:</label>  
  22.                 <label>@obj.Designation</label>  
  23.             </div>  
  24.             <div class="form-group">  
  25.                 <label>Gender:</label>  
  26.                 <label>@obj.Gender</label>  
  27.             </div>  
  28.             <div class="form-group">  
  29.                 <label>City:</label>  
  30.                 <label>@obj.City</label>  
  31.             </div>  
  32.         </div>  
  33.   
  34.     </div>  
  35.     <div class="row">  
  36.         <div class="col-md-4">  
  37.             <div class="form-group">  
  38.                 <input type="button" class="btn btn-danger" @onclick="@DeleteEmployee" value="Delete" />  
  39.                 <input type="button" class="btn btn-primary" @onclick="@Cancel" value="Cancel" />  
  40.             </div>  
  41.         </div>  
  42.     </div>  
  43. </form>  
  44.   
  45. @code {  
  46.     [Parameter]  
  47.     public string Id { getset; }  
  48.     Employee obj = new Employee();  
  49.     protected override async Task OnInitializedAsync()  
  50.     {  
  51.         obj = await Task.Run(() => employeeService.GetEmployeeAsync(Convert.ToInt32(Id)));  
  52.     }  
  53.     protected async void DeleteEmployee()  
  54.     {  
  55.         await employeeService.DeleteEmployeeAsync(obj);  
  56.         NavigationManager.NavigateTo("Employees");  
  57.     }  
  58.     void Cancel()  
  59.     {  
  60.         NavigationManager.NavigateTo("Employees");  
  61.     }  
  62. }  
Run and test the applicaton 
 
Click on employee tab you will see all the existing details in the grid 
 
Blazor Server App CRUD With Entity Framework Core In .Net 5 
 
Add the employee details and save in Database. 
 
 Blazor Server App CRUD With Entity Framework Core In .Net 5
 
 Edit the employee details
 
Blazor Server App CRUD With Entity Framework Core In .Net 5 
 
 Update the details 
 
Blazor Server App CRUD With Entity Framework Core In .Net 5 
 
 Delete operation
 
Blazor Server App CRUD With Entity Framework Core In .Net 5 
 
Here is a clear picture of the Crud Application in Blazor and I hope this article helps you... !!!
 
Keep learning .... !!!!!