Skip to main content

.NET7 | Razor Pages | EF Core | One To Many Relationships | CRUD Example

In this article, we will implement Razor Pages CRUD operation with one-to-many relationships between the tables using the Entity Framework Core.

Razor Pages:

Razor Pages is a simplified web application model. Compared with the 'MVC' template, razor pages won't have 'Controllers', which means Razor Page is a combination of  'View' and 'Model'. The route will be configured within the razor page or view. A Razor Page composed with 2 files like '*.cshtml.cs'(Model) & '*.cshtml'(view).

One-To-Many Relationship Table SQL Script:

For this demo, we will create 2 tables 'Employee'(parent table) and 'EmployeeAddresses'(child table). Between the tables, we make a one-to-many relationship which means one employee record can have multiple records in the employee address table.
Employee Table Script:
CREATE TABLE Employee(
Id int IDENTITY (1,1) NOT NULL,
FirstName varchar (200) ,
LastName varchar (200) ,
JobRole varchar(50)
CONSTRAINT PK_Employee_Id PRIMARY KEY (Id)
)
EmployeeAddresses Table Script:
Create Table EmployeeAddresses(
Id int IDENTITY (1,1) NOT NULL,
City varchar(100),
Country varchar(100),
EmployeeId int NOT NULL
CONSTRAINT PK_EmployeeAddresses_Id PRIMARY KEY (Id)
CONSTRAINT FK_Employee_Address_EmployeeId FOREIGN KEY (EmployeeId)
REFERENCES Employee (Id)
)
  • Here 'EmployeeId' is the Foreign Key.

Create A .NET 7 Razor Page Application:

Let's create a .NET 7 Razor Page sample application to accomplish our demo. We can use either Visual Studio 2022 or Visual Studio Code(using .NET CLI commands) to create the .NET 7 applications. For this demo, I'm using the 'Visual Studio Code'(using the .NET CLI commands) editor.

.NET CLI command to create razor project.
CLI command
dotnet new webapp -o Your_Project_Name

Let's explore the Razor Page project.
(1)In 'Program.cs' registered the 'AddRazorPage()' service for Razor Pages.
(2) In 'Program.cs' let's understand default middleware
  • (Line: 9-14) Here configured middlewars that needs to be run in other environment(not in development or local environment). The 'UseExceptionHandler' configured with end user friendly error page. The 'UseHsts' helps to signal the client(browser) that only secured requests(HTTPS requests) are accepted.
  • (Line:16) The 'UseHttpsRedirection' middleware helps to redirect the non HTTP request to HTTPS
  • (Line: 17) The 'UseStaticFiles' middleware to serve the files like 'js', 'css', 'images', etc
  • (Line: 19) The 'UseRouting()' enables dotnet core endpoint routing
  • (Line: 23) The 'MapRazorPages()' middleware helps to serve the razor pages by its route.
(3) Let's explore default razor pages.

  • Here '_Layout' Razor page is our master template that contains common HTML like header & footer.
  • Here '_ViewStart' contains path our '_Layout' page.
  • Here '_ViewImports' contains global namespaces
  • Here 'Error', 'Index', 'Privacy' are default razro pages.
(4) Here 'wwwroot' folder to store all static files.

Entity Framework Core:

Entity Framework Core is an Object/Relational Mapping(ORM) framework. EF Core makes database communication more fluent and easy. The 'DatabaseContext' class acts as a database from our c# code, it will contain all registered classes DbSet<TEntity>(TEntity is any POCO class that represents the table).

Install Entity Framework Core NuGet Packages:

Let's install the Entity Framework Core Nuget Packages.
CLI command
dotnet add package Microsoft.EntityFrameworkCore --version 7.0.0

Package Manager Command
NuGet\Install-Package Microsoft.EntityFrameworkCore -Version 7.0.0

Now install the SQL Server library which is dependent on the Entity Framework Core library
CLI command
dotnet add package Microsoft.EntityFrameworkCore.SqlServer --version 7.0.0

Package Manager Command
NuGet\Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 7.0.0

Create Entities With One To Many Relationships:

Let's create 'Employee' & 'EnployeeAddresses' entities in the 'Data/Entities' folders(new folders).
Data/Entities/Employee.cs:
namespace dot7.razor.crudsample.Data.Entities;

public class Employee
{
    public int Id { get; set; }
    public string? FirstName { get; set; }
    public string? LastName { get; set; }
    public string? JobRole { get; set; }
    public List<EmployeeAddresses> EmployeeAddresses { get; set; }
}
  • (Line: 9) Here 'EmployeeAddresses' property is the navigation property. Here it represents one employee who can have multiple addresses.
Data/Entities/EmployeeAddresses.cs:
namespace dot7.razor.crudsample.Data.Entities;

public class EmployeeAddresses
{
    public int Id { get; set; }
    public string? AddressType { get; set; }
    public string? City { get; set; }
    public string? Country { get; set; }
    public int EmployeeId { get; set; }

    public Employee Employee { get; set; }
}
  • (Line: 9) The 'EmployeeId' property will be our foreign key property.
  • (Line: 11) The 'Employee' is our navigation property.

Create DatabaseContext:

Let's create the DatabaseContext like 'MyWorldDbContext' in the 'Data' folder.
Data/MyWorldDbContext.cs:
using dot7.razor.crudsample.Data.Entities;
using Microsoft.EntityFrameworkCore;

namespace dot7.razor.crudsample.Data;


public class MyWorldDbContext : DbContext
{
    public MyWorldDbContext(DbContextOptions<MyWorldDbContext> context) : base(context)
    {

    }

    public DbSet<Employee> Employee { get; set; }

    public DbSet<EmployeeAddresses> EmployeeAddresses{get;set;}

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<EmployeeAddresses>()
        .HasOne(_ => _.Employee)
        .WithMany(a => a.EmployeeAddresses)
        .HasForeignKey(p => p.EmployeeId);
    }
}
  • (Line: 7) The 'Microsoft.EntityFramwork.DbContext' needs to be inherited by our 'MyWorldDbContext' to act as a Database Context class.
  • (Lin: 9) The 'Microsoft.EntityFrameworkDbContextOptions' is an instance of options that we are going to register in 'Program.cs' like 'Database Provider', 'Connectionstring', etc.
  • (Line: 14&16) All our table classes must be registered inside of our database context class with 'DbSet<T>' so that the entity framework can communicate with the table of the database.
  • (Line: 20-23) Using EF Core fluent API we are defining our one-to-many relationship between 'Employee' & 'EmployeeAddresses' classes.
Let's define the connection string in 'appsettings.Development.json' file.
appsettings.Development.json:
"ConnectionStrings": {
    "MyWorldDbConnection":"Data Source=[Your_Server_Name];Initial Catalog=[Your_Database_Name];Integrated Security=True;Connect Timeout=30"
}
Now register our database context in 'Program.cs'.
Program.cs:
using dot7.razor.crudsample.Data;
using Microsoft.EntityFrameworkCore;

builder.Services.AddDbContext<MyWorldDbContext>(options =>
{
    options.UseSqlServer(builder.Configuration.GetConnectionString("MyWorldDbConnection"));
});

Read Operation Fetch Only Employee Table Data:

Let's create a Razor Page file like 'EmployeeIndex.cshtml.cs' & 'EmployeeIndex.cshtml' files in 'Pages/Employee' folder(new folder). Implement the read operation by fetching the 'Employee' table data.
Pages/Employee/EmployeeIndex.cshtml.cs:
using dot7.razor.crudsample.Data;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;

namespace dot7.razor.crudsample.Pages.Employee;

public class EmployeeIndex : PageModel
{
    private readonly MyWorldDbContext _myWorldDbContext;
    public EmployeeIndex(MyWorldDbContext myWorldDbContext)
    {
        _myWorldDbContext = myWorldDbContext;
    }

    public List<dot7.razor.crudsample.Data.Entities.Employee> AllEmployees { get; set; }

    public async Task<IActionResult> OnGetAsync()
    {
        AllEmployees = await _myWorldDbContext.Employee.ToListAsync();
        return Page();
    }
}
  • (Line: 8) To make our 'EmployeeIndex' class as a Razor Page model it needs to inherit the 'Microsoft.AspNetCore.Mvc.RazorPages.PageModel'.
  • (Line: 11) Injected the Database context into our  Razor Page model.
  • (Line: 16) Declared a variable of a type that is collection 'Employee' to hold the data from the database and then bind the data to the UI.
  • (Line: 18-22)  The default method executed for the razor page HTTP Get request is 'OnGet' or 'OnGetAsync'. It is always ideal to have one method for each HTTP verbs like 'GET', 'POST'. There is an option to customize the name of the HTTP GET request method then it should be like 'OnGet{YourCustomNae}',  or 'OnGet{YourCustomName}Async', but if we customize the method name then we have to specify the custom name as value to the query parameter 'handlre'. So don't give the custom name unless it is required. Here in our 'OnGetAsync' method we are fetching the 'Employee' data from the database and the result assigned to 'AllEmployees' variable.
Pages/Employee/EmployeeIndex.cshtml:
@page "/employee/index"
@model dot7.razor.crudsample.Pages.Employee.EmployeeIndex

<div class="container">
    <div class="row">

        <table class="table table-striped table-hover">
            <thead>
                <tr>
                    <th scope="col">First Name</th>
                    <th scope="col">Last Name</th>
                    <th scope="col">Job Role</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var emp in Model.AllEmployees)
                {
                    <tr>
                        <th>@emp.FirstName</th>
                        <td>@emp.LastName</td>
                        <td>@emp.JobRole</td>
                    </tr>
                }
            </tbody>
        </table>
    </div>
</div>
  • (Line: 1) Using the '@page' directive we defined our razor page route.
  • (Line: 2) Defined our Model 
  • (Line: 16-23)Looping our data to bind to UI.
Now run the application and then navigate to '/employee/index'.

Read Operation To Fetch Employee And EmployeeAddresses Table Data:

Let's create the new Razor Page files like 'EmployeeDetails.cshtml' & 'EmployeeDetails.cshtml.cs'. This page displays full details of employee including the collection of addresses.
Pages/Employee/EmployeeDetails.cshtml.cs:
using dot7.razor.crudsample.Data;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;

namespace dot7.razor.crudsample.Pages.Employee;

public class EmployeeDetails : PageModel
{
    private readonly MyWorldDbContext _myWorldDbContext;
    public EmployeeDetails(MyWorldDbContext myWorldDbContext)
    {
        _myWorldDbContext = myWorldDbContext;
    }

    public dot7.razor.crudsample.Data.Entities.Employee Employee { get; set; }
    public async Task<IActionResult> OnGetAsync(int id)
    {
        Employee = await _myWorldDbContext.Employee.Include(_ => _.EmployeeAddresses)
        .Where(_ => _.Id == id).FirstOrDefaultAsync();
        return Page();
    }
}
  • (Line: 19-21) The 'Include' from the entity framework library is configured with a navigation property like 'EmployeeAddress'. The 'Include' generate a SQL join query between the 'Employee' & 'EmployeeAddressed' table.
Pages/Employee/EmployeeDetails.cshtml:
@page "/employee/details"
@model dot7.razor.crudsample.Pages.Employee.EmployeeDetails

<div class="container">
    <div class="row">
        <div class="col col-md-6 offset-md-3">
            <div class="card">
                <div class="card-body">
                    <h5 class="card-title">@Model.Employee.FirstName @Model.Employee.LastName</h5>
                    <h5 class="card-title">@Model.Employee.JobRole</h5>
                    @foreach (var item in Model.Employee.EmployeeAddresses)
                    {
                        <div class="card">
                            <div class="card-header">
                                @item.AddressType Address
                            </div>
                            <div class="card-body">
                                City - @item.City / Country - @item.Country
                            </div>
                        </div>
                    }
                </div>
            </div>
        </div>
    </div>
</div>
  • (Line: 11-21) Looping the employee addresses to bind to UI.
Now add a details link in 'EmployeeIndex' razor that helps to navigate to the 'EmployeeDetails' razor page.
Pages/Employee/EmployeeIndex.cshtml:
<!-- existing code hidden for display purpose -->
<table class="table table-striped table-hover">
	<thead>
		<tr>
			<th scope="col">Actions</th>
		</tr>
	</thead>
	<tbody>
		@foreach (var emp in Model.AllEmployees)
		{
			<tr>
				<td>
					<a asp-page="./EmployeeDetails" asp-route-id="@emp.Id">Details</a>
				</td>
			</tr>
		}
	</tbody>
</table>
  • (Line: 5) Added a new column like 'Actions'.
  • (Line: 13) Added the anchor tag to navigate for the 'EmployeeDetails' page. Here 'asp-page' & 'asp-route-id' are razor tag helpers, for 'asp-page' pass the name of the razor page file and for 'asp-route-id' pass the value for the query parameter 'id'.

Create Operation:

Let's add new Razor Page files like 'EmployeeCreate.cshtml' & 'EmployeeCreate.cshtml.cs' to implement the create opertion.
Pages/Employee/EmployeeCreate.cshtml.cs:
using dot7.razor.crudsample.Data;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace dot7.razor.crudsample.Pages.Employee;

public class EmployeeCreate : PageModel
{
    private readonly MyWorldDbContext _myWorldDbContext;
    public EmployeeCreate(MyWorldDbContext myWorldDbContext)
    {
        _myWorldDbContext = myWorldDbContext;
    }
    [BindProperty]
    public dot7.razor.crudsample.Data.Entities.Employee NewEmployee { get; set; }

    public async Task<IActionResult> OnGetAsync()
    {
        return Page();
    }

    public async Task<IActionResult> OnPostAsync()
    {
        _myWorldDbContext.Employee.Add(NewEmployee);
        await _myWorldDbContext.SaveChangesAsync();
        return Redirect("index");
    }
}
  • (Line: 14-15) Here 'NewEmployee' property of type 'Employee' is registered with the 'BindProperty' attribute. So the 'BindProperty' attribute makes our 'NewEmployee' property capture the user-entered form data.
  • (Line: 22) The 'OnPostAsync' method executes for HTTP Post request(eg: form post)
  • (Line: 24) Trying to save our form data. Since 'NewEmployee' reads form data and has a navigation property like 'EmployeeAddress', if form data contains a collection of 'EmployeeAddress' information, on saving 'Employee' data 'EmployeeAddress' data will also be saved.
  • (Line: 26) After saving finally redirect back to the index page.
Pages/Employee/EmployeeCreate.cshtml:
@page "/employee/create"
@model dot7.razor.crudsample.Pages.Employee.EmployeeCreate

<div class="container">
    <div class="row">
        <div class="col col-md-6 offset-md-3">
            <form method="post">
                <legend>Add A Employee</legend>
                <div class="mb-3">
                    <label for="txtfirstName" class="form-label">First Name</label>
                    <input asp-for="NewEmployee.FirstName" type="text" class="form-control" id="txtfirstName" />
                </div>
                <div class="mb-3">
                    <label for="txtlastName" class="form-label">Last Name</label>
                    <input asp-for="NewEmployee.LastName" type="text" class="form-control" id="txtlastName" />
                </div>
                <div class="mb-3">
                    <label for="txtjobRole" class="form-label">Job Role</label>
                    <input asp-for="NewEmployee.JobRole" type="text" class="form-control" id="txtjobRole" />
                </div>
                @for (int i = 0; i <= 1; i++)
                {
                    <div class="row">

                        <legend>Address @i</legend>
                        <div class="mb-3">
                            <label for="txtCity" class="form-label">Address Type</label>
                            <input asp-for="NewEmployee.EmployeeAddresses[i].AddressType" type="text"
                            class="form-control" />
                        </div>
                        <div class="mb-3">
                            <label for="txtCity" class="form-label">City</label>
                            <input asp-for="NewEmployee.EmployeeAddresses[i].City" type="text" class="form-control" />
                        </div>
                        <div class="mb-3">
                            <label for="txtCity" class="form-label">Country</label>
                            <input asp-for="NewEmployee.EmployeeAddresses[i].Country" type="text" class="form-control" />
                        </div>

                    </div>
                }

                <button type="submit" class="btn btn-primary">Submit</button>
            </form>
        </div>
    </div>
</div>
  • (Line: 1) The '@page' directive to define the route
  • (Line: 11&15&19) Here we can observe that 'NewEmployee' variable properties are mapped to 'asp-for' tag. The 'asp-for' tag renders as an HTML 'name' attribute that helps to post the form data.
  • (Line: 21-41) Here 2 address forms are trying to render by looping it.
  • (Line: 28&33&37)Here are our forms for the 'EmployeeAddress' collection and configured with 'asp-for'.
In the 'EmployeeIndex.cshtml' add a link for navigating to 'EmployeeCreate.cshtml'
Pages/Employee/EmployeeIndex.cshtml:
<div class="col col-md-4 offset-md-4">
	<a asp-page="./EmployeeCreate" >Add New Employee</a>
</div>
(Step 1)

(Step 2)

(Step 3)

Update Operation:

Let's create new Razor Page files like 'EmployeeUpdate.cshtml.cs' & 'EmployeeUpdate.cshtml'.
Pages/Employee/EmployeeUpdate.cshtml.cs:
using dot7.razor.crudsample.Data;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;

namespace dot7.razor.crudsample.Pages.Employee;

public class EmployeeUpdate : PageModel
{
    private readonly MyWorldDbContext _myWorldDbContext;
    public EmployeeUpdate(MyWorldDbContext myWorldDbContext)
    {
        _myWorldDbContext = myWorldDbContext;
    }
    [BindProperty]
    public dot7.razor.crudsample.Data.Entities.Employee EmployeeToUpdate { get; set; }

    public async Task<IActionResult> OnGetAsync(int id)
    {
        EmployeeToUpdate = await _myWorldDbContext.Employee.Include(_ => _.EmployeeAddresses)
        .Where(_ => _.Id == id).FirstOrDefaultAsync();
        return Page();
    }

    public async Task<IActionResult> OnPostAsync()
    {
        _myWorldDbContext.Employee.Update(EmployeeToUpdate);
        await _myWorldDbContext.SaveChangesAsync();
        return Redirect("index");
    }
}
  • (Line: 18-23) The 'OnGetAsync' method is executed for HTTP GET request. Here we fetch the 'Employee' by 'id' and also fetch it 'EmployeeAddress' data to display it on the form. The 'Include' ef-core method loads the child table information
  • (Line: 25-30) The 'OnPostAsync' method is executed for HTTP POST requests. The 'Update' method updates both 'Employee' & 'EmployeeAddress' data.
Pages/Employee/EmployeeUpdate.csthml:
@page "/employee/update"
@model dot7.razor.crudsample.Pages.Employee.EmployeeUpdate


<div class="container">
    <div class="row">
        <div class="col col-md-6 offset-md-3">
            <form method="post">
                <legend>Update Employee</legend>
                <input type="hidden" asp-for="EmployeeToUpdate.Id">
                <div class="mb-3">
                    <label for="txtfirstName" class="form-label">First Name</label>
                    <input asp-for="EmployeeToUpdate.FirstName" type="text" class="form-control" id="txtfirstName" />
                </div>
                <div class="mb-3">
                    <label for="txtlastName" class="form-label">Last Name</label>
                    <input asp-for="EmployeeToUpdate.LastName" type="text" class="form-control" id="txtlastName" />
                </div>
                <div class="mb-3">
                    <label for="txtjobRole" class="form-label">Job Role</label>
                    <input asp-for="EmployeeToUpdate.JobRole" type="text" class="form-control" id="txtjobRole" />
                </div>
                @for (int i = 0; i <= 1; i++)
                {
                    <div class="row">

                        <legend>Address @i</legend>
                        <input type="hidden" asp-for="EmployeeToUpdate.EmployeeAddresses[i].Id">
                        <div class="mb-3">
                            <label for="txtCity" class="form-label">Address Type</label>
                            <input asp-for="EmployeeToUpdate.EmployeeAddresses[i].AddressType" type="text"
                            class="form-control" />
                        </div>
                        <div class="mb-3">
                            <label for="txtCity" class="form-label">City</label>
                            <input asp-for="EmployeeToUpdate.EmployeeAddresses[i].City" type="text" class="form-control" />
                        </div>
                        <div class="mb-3">
                            <label for="txtCity" class="form-label">Country</label>
                            <input asp-for="EmployeeToUpdate.EmployeeAddresses[i].Country" type="text" class="form-control" />
                        </div>

                    </div>
                }

                <button type="submit" class="btn btn-primary">Submit</button>
            </form>
        </div>
    </div>
</div>
  • (Line: 10&28) The only difference between 'create' and update forms are 'Id' values. In the 'Update' form we have to store our 'Id' values in the hidden field for both 'Employee'  & 'EmployeeAddress' table
Let's add the 'update' anchor tag in 'EmployeeIndex' so that we can navigate to the 'EmployeeUpdate' page.
Pages/Employee/EmployeeIndex.cshtml:
<a asp-page="./EmployeeUpdate" asp-route-id="@emp.Id">Update</a>
(Step 1)

(Step 2)

Delete Operation:

Let's create new Razor Pages files like 'EmployeDelete.cshtml' & 'EmployeeDelete.cshtml.cs' to implement the delete operation.
Pages/Employee/EmployeeDelete.cshtml.cs:
using dot7.razor.crudsample.Data;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;

namespace dot7.razor.crudsample.Pages.Employee;

public class EmployeeDelete : PageModel
{
    private readonly MyWorldDbContext _myWorldDbContext;
    public EmployeeDelete(MyWorldDbContext myWorldDbContext)
    {
        _myWorldDbContext = myWorldDbContext;
    }

    public dot7.razor.crudsample.Data.Entities.Employee Employee { get; set; }

    public async Task<IActionResult> OnGetAsync(int id)
    {
        Employee = await _myWorldDbContext.Employee.Include(_ => _.EmployeeAddresses)
        .Where(_ => _.Id == id).FirstOrDefaultAsync();
        return Page();
    }

    public async Task<IActionResult> OnPostAsync(int id)
    {
        var employeeToDelete = await _myWorldDbContext.Employee.Include(_ => _.EmployeeAddresses)
        .Where(_ => _.Id == id).FirstOrDefaultAsync();

        _myWorldDbContext.Employee.Remove(employeeToDelete);
        await _myWorldDbContext.SaveChangesAsync();
        return Redirect("index");
    }
}
  • (Line: 18-23) In 'OnGetAsync' method fetches the item to display on our delete page.
  • (Line: 25-34) In 'OnPostAsync' method fetch 'Employee' record along with 'EmployeeAddress' records and then delete by passing them to 'Reomve' method.
Pages/Employee/EmployeeDelete.cshtml:
@page "/employee/delete"
@model dot7.razor.crudsample.Pages.Employee.EmployeeDelete

<div class="container">
    <div class="row">
        <div class="col col-md-6 offset-md-3">
            <div class="card">
                <div class="card-body">
                    <h5 class="card-title">@Model.Employee.FirstName @Model.Employee.LastName</h5>
                    <h5 class="card-title">@Model.Employee.JobRole</h5>
                    @foreach (var item in Model.Employee.EmployeeAddresses)
                    {
                        <div class="card">
                            <div class="card-header">
                                @item.AddressType Address
                            </div>
                            <div class="card-body">
                                City - @item.City / Country - @item.Country
                            </div>
                        </div>
                    }
                </div>
                <div class="card-body">
                    <form method="post">
                        <button type="submit" class="btn btn-primary">Confirm Delete</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
  • (Line: 24-26) Our 'Confirm Delete' button wrapped around a 'form' tag so that on clicking button we will invoke our 'OnPostAsync()' method in 'EmployeeDelete.cshtml.cs' file.
Now let's add the anchor tag link for 'Delete' in our 'EmployeeIndex.cshtml'.
Pages/EmployeeIndex.cshtml:
<a asp-page="./EmployeeDelete" asp-route-id="@emp.Id">Delete</a>

Support Me!
Buy Me A Coffee PayPal Me

Video Session:

Wrapping Up:

Hopefully, I think this article delivered some useful information on .NET 7 Razor Pages CRUD operations. I love to have your feedback, suggestions, and better techniques in the comment section below.

Refer:

Follow Me:

Comments

Popular posts from this blog

Angular 14 Reactive Forms Example

In this article, we will explore the Angular(14) reactive forms with an example. Reactive Forms: Angular reactive forms support model-driven techniques to handle the form's input values. The reactive forms state is immutable, any form filed change creates a new state for the form. Reactive forms are built around observable streams, where form inputs and values are provided as streams of input values, which can be accessed synchronously. Some key notations that involve in reactive forms are like: FormControl - each input element in the form is 'FormControl'. The 'FormControl' tracks the value and validation status of form fields. FormGroup - Track the value and validate the state of the group of 'FormControl'. FormBuilder - Angular service which can be used to create the 'FormGroup' or FormControl instance quickly. Form Array - That can hold infinite form control, this helps to create dynamic forms. Create An Angular(14) Application: Let'

.NET 7 Web API CRUD Using Entity Framework Core

In this article, we are going to implement a sample .NET 7 Web API CRUD using the Entity Framework Core. Web API: Web API is a framework for building HTTP services that can be accessed from any client like browser, mobile devices, and desktop apps. In simple terminology API(Application Programming Interface) means an interface module that contains programming functions that can be requested via HTTP calls either to fetch or update data for their respective clients. Some of the Key Characteristics of API: Supports HTTP verbs like 'GET', 'POST', 'PUT', 'DELETE', etc. Supports default responses like 'XML' and 'JSON'. Also can define custom responses. Supports self-hosting or individual hosting, so that all different kinds of apps can consume it. Authentication and Authorization are easy to implement. The ideal platform to build the REST full services. Install The SQL Server And SQL Management Studio: Let's install the SQL server on our l

ReactJS(v18) JWT Authentication Using HTTP Only Cookie

In this article, we will implement the ReactJS application authentication using the HTTP-only cookie. HTTP Only Cookie: In a SPA(Single Page Application) Authentication JWT token either can be stored in browser 'LocalStorage' or in 'Cookie'. Storing the JWT token inside of the cookie then the cookie should be HTTP Only. The HTTP-ONly cookie nature is that it will be only accessible by the server application. Client apps like javascript-based apps can't access the HTTP-Only cookie. So if we use the authentication with HTTP-only JWT cookie then we no need to implement the custom logic like adding authorization header or storing token data, etc at our client application. Because once the user authenticated cookie will be automatically sent to the server by the browser on every API call. Authentication API: To authenticate our client application with JWT HTTP-only cookie, I developed a NetJS(which is a node) Mock API. Check the GitHub link and read the document on G

.NET6 Web API CRUD Operation With Entity Framework Core

In this article, we are going to do a small demo on AspNetCore 6 Web API CRUD operations. What Is Web API: Web API is a framework for building HTTP services that can be accessed from any client like browser, mobile devices, desktop apps. In simple terminology API(Application Programming Interface) means an interface module that contains a programming function that can be requested via HTTP calls to save or fetch the data for their respective clients. Some of the key characteristics of API: Supports HTTP verbs like 'GET', 'POST', 'PUT', 'DELETE', etc. Supports default responses like 'XML' and 'JSON'. Also can define custom responses. Supports self-hosting or individual hosting, so that all different kinds of apps can consume it. Authentication and Authorization are easy to implement. The ideal platform to build REST full services. Create A .NET6 Web API Application: Let's create a .Net6 Web API sample application to accomplish our

Angular 14 State Management CRUD Example With NgRx(14)

In this article, we are going to implement the Angular(14) state management CRUD example with NgRx(14) NgRx Store For State Management: In an angular application to share consistent data between multiple components, we use NgRx state management. Using NgRx state helps to avoid unwanted API calls, easy to maintain consistent data, etc. The main building blocks for the NgRx store are: Actions - NgRx actions represents event to trigger the reducers to save the data into the stores. Reducer - Reducer's pure function, which is used to create a new state on data change. Store - The store is the model or entity that holds the data. Selector - Selector to fetch the slices of data from the store to angular components. Effects - Effects deals with external network calls like API. The effect gets executed based the action performed Ngrx State Management flow: The angular component needs data for binding.  So angular component calls an action that is responsible for invoking the API call.  Aft

Angular 14 Crud Example

In this article, we will implement CRUD operation in the Angular 14 application. Angular: Angular is a framework that can be used to build a single-page application. Angular applications are built with components that make our code simple and clean. Angular components compose of 3 files like TypeScript File(*.ts), Html File(*.html), CSS File(*.cs) Components typescript file and HTML file support 2-way binding which means data flow is bi-directional Component typescript file listens for all HTML events from the HTML file. Create Angular(14) Application: Let's create an Angular(14) application to begin our sample. Make sure to install the Angular CLI tool into our local machine because it provides easy CLI commands to play with the angular application. Command To Install Angular CLI npm install -g @angular/cli Run the below command to create the angular application. Command To Create Angular Application ng new name_of_your_app Note: While creating the app, you will see a noti

Unit Testing Asp.NetCore Web API Using xUnit[.NET6]

In this article, we are going to write test cases to an Asp.NetCore Web API(.NET6) application using the xUnit. xUnit For .NET: The xUnit for .Net is a free, open-source, community-focused unit testing tool for .NET applications. By default .Net also provides a xUnit project template to implement test cases. Unit test cases build upon the 'AAA' formula that means 'Arrange', 'Act' and 'Assert' Arrange - Declaring variables, objects, instantiating mocks, etc. Act - Calling or invoking the method that needs to be tested. Assert - The assert ensures that code behaves as expected means yielding expected output. Create An API And Unit Test Projects: Let's create a .Net6 Web API and xUnit sample applications to accomplish our demo. We can use either Visual Studio 2022 or Visual Studio Code(using .NET CLI commands) to create any.Net6 application. For this demo, I'm using the 'Visual Studio Code'(using the .NET CLI command) editor. Create a fo

Part-1 Angular JWT Authentication Using HTTP Only Cookie[Angular V13]

In this article, we are going to implement a sample angular application authentication using HTTP only cookie that contains a JWT token. HTTP Only JWT Cookie: In a SPA(Single Page Application) Authentication JWT token either can be stored in browser 'LocalStorage' or in 'Cookie'. Storing JWT token inside of the cookie then the cookie should be HTTP Only. The HTTP-Only cookie nature is that it will be only accessible by the server application. Client apps like javascript-based apps can't access the HTTP-Only cookie. So if we use authentication with HTTP only JWT cookie then we no need to implement custom logic like adding authorization header or storing token data, etc at our client application. Because once the user authenticated cookie will be automatically sent to the server by the browser on every API call. Authentication API: To implement JWT cookie authentication we need to set up an API. For that, I had created a mock authentication API(Using the NestJS Se

ReactJS(v18) Authentication With JWT AccessToken And Refresh Token

In this article, we are going to do ReactJS(v18) application authentication using the JWT Access Token and Refresh Token. JSON Web Token(JWT): JSON Web Token is a digitally signed and secured token for user validation. The JWT is constructed with 3 important parts: Header Payload Signature Create ReactJS Application: Let's create a ReactJS application to accomplish our demo. npx create-react-app name-of-your-app Configure React Bootstrap Library: Let's install the React Bootstrap library npm install react-bootstrap bootstrap Now add the bootstrap CSS reference in 'index.js'. src/index.js: import 'bootstrap/dist/css/bootstrap.min.css' Create A React Component 'Layout': Let's add a React component like 'Layout' in 'components/shared' folders(new folders). src/components/shared/Layout.js: import Navbar from "react-bootstrap/Navbar"; import { Container } from "react-bootstrap"; import Nav from "react-boot

A Small Guide On NestJS Queues

NestJS Application Queues helps to deal with application scaling and performance challenges. When To Use Queues?: API request that mostly involves in time taking operations like CPU bound operation, doing them synchronously which will result in thread blocking. So to avoid these issues, it is an appropriate way to make the CPU-bound operation separate background job.  In nestjs one of the best solutions for these kinds of tasks is to implement the Queues. For queueing mechanism in the nestjs application most recommended library is '@nestjs/bull'(Bull is nodejs queue library). The 'Bull' depends on Redis cache for data storage like a job. So in this queueing technique, we will create services like 'Producer' and 'Consumer'. The 'Producer' is used to push our jobs into the Redis stores. The consumer will read those jobs(eg: CPU Bound Operations) and process them. So by using this queues technique user requests processed very fastly because actually