In this article, we are going to implement CRUD operations in .Net5 Blazor Server application.
Entity Framework Core:
step2:
Blazor Server:
Blazor Server is a single-page application. At the server, a pre-rendered HTML output of the page will be delivered to the user browsers. Any UI update, event handling, javascript calls will carry over by a SignalR connection to the server. So application updates or depends on the continuous connection of the SignalR.So Blazor Server is a single-page application that will be made of c#. Since the blazor server only outputs the pre-rendered HTML to the client, so there is no c# code downloading into user browsers like in Blazor Webassembly(c# code downloaded and runs in browser for blazor webassembly application).
Role Of SignalR Connection:
A Blazor Server application works over a SignalR connection. A Blazor Server application creates a UI State memory at the server which will be interacted by the SignalR connections. If a SignalR connection got interrupted, then the client tries to maintain the same state of the application by initiating a new SignalR connection and uses the existing UI state memory at the server. App routing changes, event changes, data changes everything will be carried out by the SignalR connection without any page reloads.
Each browser screen or browser tab has its own SignalR connection channels and UI states at the application. So each browser screen or browser tab acts as an individual user request.
Blazor Components:
Blazor Server application built on top of the 'Blazor Components'. A blazor component file will be created like 'Example.razor', the file extension is '.razor'. A blazor component file consists of both c# and razor syntaxes. Blazor component also provides an option to split the files like 'Example.razor'(contains all razor code) and 'Example.razor.cs'(contains all c# code).
Create A .Net5 Blazor Server Application:
Let's start our learning journey by creating a .Net5 Blazor Server Application sample project.
Visual Studio users can easily create .Net5 Blazor Server Application. On creating application visual studio UI shows different application template options in that we have to select 'Blazor Server App'.
Here for this demo, I'm going to use Visual Studio Code editor and .NET CLI commands. Run the below .NET CLI command to create Blazor Server App.
CLI Command To Blazor Server Application:
dotnet new blazorserver -n your_project_name
After creating an application, few things we need to aware of about the project:Register RazorPages And Blazor Server Service- In the 'Startup.cs' file registered with 'AddRazorPages' and 'AddServerSideBlazor' services to gain dependency injection benefits.
Endpoint Routing Middleware - In the 'Starup.cs' file configured endpoint middleware with 'MapBlazorHub'(for SignalR routing) and 'MapFallbackToPage' (for Blazor Server routing).
Pages/_Host.cshtml - It is the entry file for any of our first requests to the server. It renders the default blazor component like 'App.razor'.
App.razor - This is then the entry Blazor component. It contains a default blazor router component like 'Router'. The 'Router' component handles the user request and loads the appropriate Blazor Page components.
MainLayout.razor and NavMenu.razor - Default layout blazor component.
Pages Folder - Area to create blazor components
wwwroot Folder - Area to store all static files like js, css, images, etc.
Entity Framework Core:
Entity Framework Core is an Object/Relational Mapping(ORM) framework. EF Core makes database communication more fluent and easy.
EF Core supports:
Code First Approach means first we will create c# POCO classes and then create the database tables. Code First Approach has one more sub-category like 'Code First With Existing Database'. So the 'Code First With Existing Database' can work with the already created tables in the database which is an ideal choice for real-time development. Our demo will be implemented using 'Code First With Existing Database'.
- Database First Approach.
- Code First Approach.
Install EF Core Nuget:
Now install ef core and SQL ef core extension Nuget package into our application.
Package Manager(Visual Studio):
Install-Package Microsoft.EntityFrameworkCore -Version 5.0.6
Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 5.0.6
CLI Commands(Visual Studio Code):
dotnet add package Microsoft.EntityFrameworkCore --version 5.0.6
dotnet add package Microsoft.EntityFrameworkCore.SqlServer --version 5.0.6
Sample SQL Script:
To follow the demo, run the SQL script to generate the table.
CREATE TABLE [dbo].[Gadgets]( [Id] [int] IDENTITY(1,1) NOT NULL, [ProductName] [varchar](max) NULL, [Brand] [varchar](max) NULL, [Cost] [decimal](18, 0) NOT NULL, [ImageName] [varchar](1024) NULL, [Type] [varchar](128) NULL, [CreatedDate] [datetime] NULL, [ModifiedDate] [datetime] NULL, PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
Setup Entity Framework Core DbContext:
First, let's create POCO class that represents our table. So let's create a new folder 'Entities' inside of the Data Folder, then inside of the 'Entities' folder creates our POCO class.
Data/Entities/Gadgets.cs:
namespace Dotnet5.BlazorServer.CRUD.EFCore.Data.Entities
{
public class Gadgets
{
public int Id { get; set; }
public string ProductName { get; set; }
public string Brand { get; set; }
public decimal Cost { get; set; }
public string Type { get; set; }
}
}
In EF Core DbContext is like a database that manages all POCO classes(classes represent tables). Inside the 'Data' folder create a context class.Data/MyWorldDbContext.cs:
using Dotnet5.BlazorServer.CRUD.EFCore.Data.Entities; using Microsoft.EntityFrameworkCore; namespace Dotnet5.BlazorServer.CRUD.EFCore.Data { public class MyWorldDbContext : DbContext { public MyWorldDbContext(DbContextOptions<MyWorldDbContext> options) : base(options) { } public DbSet<Gadgets> Gadgets { get; set; } } }Add database connection string into 'appsetting.Development.json'.
appsetings.Development.json:
"ConnectionStrings":{ "MyWorldDbConnection":"your_connection" }Register 'MyWorlDbContext' into the dependency services.
services.AddDbContext<MyWorldDbContext>(options => { options.UseSqlServer(Configuration.GetConnectionString("MyWorldDbConnection")); });
Read Operation:
First, let's register some namespaces into the '_Imports.razor' file.
_Imports.razor:
@using Dotnet5.BlazorServer.CRUD.EFCore.Data @using Dotnet5.BlazorServer.CRUD.EFCore.Data.Entities @using Microsoft.EntityFrameworkCore
For our demo, we will use the existing blazor page component that is 'Pages/Index.razor'. So let's start working on implementing 'Read Operation.
Pages/Index.razor:(HTML Part)
@page "/" @inject MyWorldDbContext _myWorldDbContext; <div> <table class="table table-bordered"> <thead> <tr> <th scope="col">Id</th> <th scope="col">Product Name</th> <th scope="col">Brand</th> <th scope="col">Cost</th> <th scope="col">Type</th> </tr> </thead> <tbody> @foreach (var item in AllGadgets) { <tr> <th scope="row">@item.Id</th> <td>@item.ProductName</td> <td>@item.Brand</td> <td>@item.Cost</td> <td>@item.Type</td> </tr> } </tbody> </table> </div>
- (Line: 1) Routing to a blazor component should be defined using the '@page' directive.
- (Line: 2) Injected our database context using the '@Inject' directive.
- (Line: 16-25) The 'AllGadgets' is a c# property that contains a collection. Here binding the data to the bootstrap table.
@code { public List<Gadgets> AllGadgets = new List<Gadgets>(); protected override async Task OnInitializedAsync() { AllGadgets = await _myWorldDbContext.Gadgets.OrderByDescending(_ => _.Id).ToListAsync(); } }
- (Line: 1) The entire c# code must be encapsulated inside of the '@code' directive.
- (Line: 2) Declared and initialized a collection property like 'AllGadgets'.
- By default, it always recommended to use asynchronous calls to scale up the application. So for a method to we must use the 'async' keyword and output must be either 'Task' or 'Task<T>' and inside the method, every asynchronous job must be prefixed with the 'await' keyword.
- (Line: 4-7) The 'OnInitializedAsync' is the default life cycle method of Blazor Server. Here fetching all data from the database and assigning to the 'AllGadgets' property.
Create Operation:
Bootstrap modal will be used for 'Create Operation'. So first let's add the Bootstrap 'js' and JQuery 'js' into the '_Host.cshtml'.
Pages/_Host.cshtml:(Above the closing body tag)
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>In Blazor c# code can invoke the javascript code that is called 'Blazor JavaScript Interoperability'. Now we have to write some javascript code to open and close the Bootstrap Modal. That javascript code will be called from the c# code in upcoming steps. So in 'wwwroot' folder add a new folder like 'js' and then add a new file like 'app.js'.
wwwroot/js/app.js:
window.global = { openModal: function (modalId) { modalId = "#" + modalId; $(modalId).modal("show"); }, closeModal: function (modalId) { modalId = "#" + modalId; $(modalId).modal("hide"); }, };
- Here written javascript code to open the bootstrap modal by its HTML id value.
Pages/_Host.csthml:
<script src="js/app.js"></script>Now let's add our 'Create Operation' changes onto the 'Index.razor' component.
Index.razor:(HTML Part)
@page "/" @inject MyWorldDbContext _myWorldDbContext; @inject IJSRuntime _jsRuntime; <!-- Some code hidden for display purpose --> <button class="btn btn-primary" @onclick='@(e => CreateOrUpdateOpenModal(0))'>Add</button> <div> <table class="table table-bordered"> </table> </div> <div class="modal fade" id="createOrupdateModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">@CreateOrUpdateTitle</h5> </div> <div class="modal-body"> <div class="mb-3"> <label for="txtProductName" class="form-label">Product Name</label> <input @bind="FormPayload.ProductName" type="text" class="form-control" id="txtProductName"> </div> <div class="mb-3"> <label for="txtBrand" class="form-label">Brand</label> <input @bind="FormPayload.Brand" type="text" class="form-control" id="txtBrand"> </div> <div class="mb-3"> <label for="txtCost" class="form-label">Cost</label> <input @bind="FormPayload.Cost" type="text" class="form-control" id="txtCost"> </div> <div class="mb-3"> <label for="txtType" class="form-label">Type</label> <input @bind="FormPayload.Type" type="text" class="form-control" id="txtType"> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" @onclick='@(e => CloseModal("global.closeModal", "createOrupdateModal"))' data-bs-dismiss="modal">Close</button> <button type="button" class="btn btn-success" @onclick="Save">Save</button> </div> </div> </div> </div>
- (Line: 3) Injected 'IJSRuntime' that helps to invoke the javascript code from the c# code.
- (Line: 5) Created 'Add' button. Here button registered with c# method to 'onclick' event. To use c# method that has parameters we need to call like delegate(eg: e => method_name(param1)) in the HTML.
- (Line: 13-44) Add the Bootstrap Modal Html. Our Bootstrap Modal popup furnished with all HTML input fields for creating a new record. To achieve a 2-way binding input HTML field must be decorated with the '@bind' directive.
- (Line: 17) Rendering popup title dynamically using the property 'CreateOrUpdateTitle'. So that same popup can be used for Edit operation as well in the coming steps.
- (Line: 38-39) Added the popup close button and its click event registered with a method like 'CloseModal'.
- (Line: 40) Added the popup save button and its click event registered with a method like 'Save'.
@code { public List<Gadgets> AllGadgets = new List<Gadgets>(); public Gadgets FormPayload = new Gadgets(); public string CreateOrUpdateTitle = string.Empty; protected override async Task OnInitializedAsync() { AllGadgets = await _myWorldDbContext.Gadgets.OrderByDescending(_ => _.Id).ToListAsync(); } public async Task CreateOrUpdateOpenModal(int gadgetId) { if (gadgetId == 0) { CreateOrUpdateTitle = "Create A Gadget"; FormPayload = new Gadgets(); await _jsRuntime.InvokeVoidAsync("global.openModal", "createOrupdateModal"); } } public async Task CloseModal(string jsMethodName, string popupHtmlId) { await _jsRuntime.InvokeVoidAsync(jsMethodName, popupHtmlId); } public async Task Save() { if (FormPayload.Id == 0) { _myWorldDbContext.Gadgets.Add(FormPayload); await _myWorldDbContext.SaveChangesAsync(); } AllGadgets.Insert(0, FormPayload); await CloseModal("global.closeModal", "createOrupdateModal"); } }
- (Line: 5) Added property 'FormPayload' of type 'Gadgets'. This 'FormPayload' property will be utilized by the input fields of our Bootstrap Modal for 2-way binding.
- (Line: 6) Added the property 'CreateOrUpdateTitle' to dynamically add the title to Bootstrap Modal.
- (Line: 12-20) Method to open the bootstrap modal on clicking the 'Add' button.
- (Line: 16) Defining the title for our bootstrap modal.
- (Line: 17) Since it creates a new record, so will assign an empty memory to our 'FormPayload' property.
- (Line: 18) Using 'JSRuntime' invoking the javascript method. So for the method 'InvokeVoidAsync', the first parameter will be the javascript function name and the second parameter will be the input parameters array for the javascript method.
- (Line: 22-25) Method to close the bootstrap modal. Here it was written in a generic way so any number of popups can use this method as a close event.
- (Line: 27-36) The 'Save' method used to create new records into the database.
- (Line: 29) Checking the 'Id' value because 'Save' method we will use for both 'Create' and 'Update' operations. If the 'Id' value is '0' then it is a 'Create' operation.
- (Line: 31-32) Saving the new record into the database.
- (Line: 34) Added the newly created or update record into the 'AllGadgets' collection. So our table gets updated with newly created or updated data.
- (Line: 35) Finally closing the modal.
step3:
Update Operation:
Now let's implement our logic to fulfill our 'Update Operation'.
Pages/Index.razor:(HTML Part)
<!-- Code hidden for display purpose --> <div> <table class="table table-bordered"> <thead> <tr> <th scope="col">Actions</th> </tr> </thead> <tbody> @foreach (var item in AllGadgets) { <tr> <td> <button class="btn btn-primary" @onclick='@(e => CreateOrUpdateOpenModal(item.Id))'>Edit</button> </td> </tr> } </tbody> </table> </div>
- (Line: 6) Created a new table column like 'Actions'.
- (Line: 14) Added the edit button for each record in the table. So here we will use the same methods that are used in 'Create Operation'.
@code { public List<Gadgets> AllGadgets = new List<Gadgets>(); public Gadgets FormPayload = new Gadgets(); public string CreateOrUpdateTitle = string.Empty; protected override async Task OnInitializedAsync() { AllGadgets = await _myWorldDbContext.Gadgets.OrderByDescending(_ => _.Id).ToListAsync(); } public async Task CreateOrUpdateOpenModal(int gadgetId) { if (gadgetId == 0) { CreateOrUpdateTitle = "Create A Gadget"; FormPayload = new Gadgets(); } else { CreateOrUpdateTitle = "Update The Gadget"; FormPayload = await _myWorldDbContext.Gadgets.Where(_ => _.Id == gadgetId).FirstOrDefaultAsync(); } await _jsRuntime.InvokeVoidAsync("global.openModal", "createOrupdateModal"); } public async Task CloseModal(string jsMethodName, string popupHtmlId) { await _jsRuntime.InvokeVoidAsync(jsMethodName, popupHtmlId); } public async Task Save() { if (FormPayload.Id == 0) { _myWorldDbContext.Gadgets.Add(FormPayload); await _myWorldDbContext.SaveChangesAsync(); } else { _myWorldDbContext.Update(FormPayload); await _myWorldDbContext.SaveChangesAsync(); AllGadgets = AllGadgets.Where(_ => _.Id != FormPayload.Id).ToList(); } AllGadgets.Insert(0, FormPayload); await CloseModal("global.closeModal", "createOrupdateModal"); } }
- (Line: 21-22) Updating the 'CreateOrUpdateTitle' property as per the operation type. Updating the 'FormPayload' with data fetched from the database with help of the 'gadgetId' value.
- (Line: 41-42) Updating the Dbcontext with our record to be updated.
- (Line: 43) Remove the record that is updated from the old collection 'AllGadgets'.
step2:
step3:
Delete Operation:
Now let's implement our logic for 'Delete Operation'.
Pages/Index.razor:(HTML Part)
<!-- Some code hidden for display purpose --> <div> <table class="table table-bordered"> <tbody> @foreach (var item in AllGadgets) { <tr> <td> <button class="btn btn-primary" @onclick='@(e => CreateOrUpdateOpenModal(item.Id))'>Edit</button> | <button class="btn btn-danger" @onclick='@(e => OpenDeleteConfrimationModal(item.Id))'>Delete</button> </td> </tr> } </tbody> </table> </div> <div class="modal fade" id="deleteGadgetModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-body"> <h4>Are you sure, you want to delete?</h4> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" @onclick='@(e => CloseModal("global.closeModal", "deleteGadgetModal"))' data-bs-dismiss="modal">Close</button> <button type="button" class="btn btn-danger" @onclick='ConfirmDelete'>Confirm Delete</button> </div> </div> </div> </div>
- (Line: 11-12) Add the new button like 'Delete'. Click event registered with method 'OpenDeleteConfirmationModal'.
- (Line: 20-35) Add a new bootstrap modal for the delete confirmation.
- (Line: 31) Delete button added and registered with 'ConfirmDelete' method.
@code { public List<Gadgets> AllGadgets = new List<Gadgets>(); public Gadgets FormPayload = new Gadgets(); public string CreateOrUpdateTitle = string.Empty; public int GadgetIdToRemove = 0; protected override async Task OnInitializedAsync() { AllGadgets = await _myWorldDbContext.Gadgets.OrderByDescending(_ => _.Id).ToListAsync(); } public async Task CreateOrUpdateOpenModal(int gadgetId) { if (gadgetId == 0) { CreateOrUpdateTitle = "Create A Gadget"; FormPayload = new Gadgets(); } else { CreateOrUpdateTitle = "Update The Gadget"; FormPayload = await _myWorldDbContext.Gadgets.Where(_ => _.Id == gadgetId).FirstOrDefaultAsync(); } await _jsRuntime.InvokeVoidAsync("global.openModal", "createOrupdateModal"); } public async Task CloseModal(string jsMethodName, string popupHtmlId) { await _jsRuntime.InvokeVoidAsync(jsMethodName, popupHtmlId); } public async Task Save() { if (FormPayload.Id == 0) { _myWorldDbContext.Gadgets.Add(FormPayload); await _myWorldDbContext.SaveChangesAsync(); } else { _myWorldDbContext.Update(FormPayload); await _myWorldDbContext.SaveChangesAsync(); AllGadgets = AllGadgets.Where(_ => _.Id != FormPayload.Id).ToList(); } AllGadgets.Insert(0, FormPayload); await CloseModal("global.closeModal", "createOrupdateModal"); } public async Task OpenDeleteConfrimationModal(int gadgetId) { GadgetIdToRemove = gadgetId; await _jsRuntime.InvokeVoidAsync("global.openModal", "deleteGadgetModal"); } public async Task ConfirmDelete() { var gadtetToDelete = await _myWorldDbContext.Gadgets.Where(_ => _.Id == GadgetIdToRemove).FirstOrDefaultAsync(); _myWorldDbContext.Gadgets.Remove(gadtetToDelete); await _myWorldDbContext.SaveChangesAsync(); AllGadgets = AllGadgets.Where(_ => _.Id != GadgetIdToRemove).ToList(); await CloseModal("global.closeModal", "deleteGadgetModal"); } }
- (Line: 8) Added variable 'GadgetIdToRemove' to store the 'Id' value of the record that needs to be deleted.
- (Line: 51-55) Opens the delete confirmation popup.
- (Line: 57-64) The 'ConfirmDelete' method to delete the record from the database.
Video Session:
Support Me!
Buy Me A Coffee
PayPal Me
Wrapping Up:
Hopefully, I think this article delivered some useful information on .Net5 Blazor Server CRUD operation with the entity framework. I love to have your feedback, suggestions, and better techniques in the comment section below.
don't you think it might be good somehow to allow "printing" ?
ReplyDeleteI just can't do that because of the "trimmed " source code in those magic code boxes
which inhibit seeing the full lenght of the code lines