Introduction to Entity Framework Core in .NET 8: Building a Simple CRUD Blazor Web App

Introduction to Entity Framework Core in .NET 8: Building a Simple CRUD Blazor Web App

Microsoft has always been a pioneer in technological innovations and has consistently introduced features and technologies that streamline development for programmers. Development using these technologies has become faster and easier. With .NET 8, Microsoft has addressed major security issues and reduced coding complexity with new shorthand commands.

In this article, a simple web application is built using Blazor Server and Entity Framework Core. Entity Framework Core is a modern, lightweight, and cross-platform Object-Relational Mapper (ORM) for .NET that allows developers to interact with databases using .NET objects. It simplifies data access by enabling developers to work with databases using strongly-typed LINQ queries rather than writing raw SQL. EF Core supports multiple database providers, including SQL Server, SQLite, PostgreSQL, and MySQL, and can handle complex data models through features like migrations, change tracking, and lazy loading.


Getting Started

The following demonstrate the use of Entity Framework Core's code-first approach to create the database and then the CRUD operation will be performed respectively. In this instance, a single Employee entity will be created with some of its key attributes including name, age and designation.

Before proceeding, make sure that your system has the following prerequisites:

  • Microsoft .NET 8 SDK
  • SQL Server Management Studio
  • Visual Studio 2022 (with ASP.NET and web development toolkit installed)

To begin, create a new Blazor web app project in .NET 8.0, and name it EmployeeCRUD.

Once you have successfully created a project named EmployeeCRUD, right click the project from your solution explorer and download the latest versions of the following NuGet packages:

Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools        

Again, right-click on your project and add a new folder named Models. For the sake of this demo project, we will be adding the model and business logic in a single project. However, it is advisable to create different Class Library projects for models and business logic respectively.

Now, right-click the Models folder and add a new C# class named Employee. Again, create another class and name it EmployeeDbContext. Your Models folder should look like this:

Your Employee.cs file should have the following code:

namespace EmployeeCRUD.Models
{
    public class Employee
    {
        public Guid Id { get; set; }
        public string? Name { get; set; }
        public int age { get; set; }
        public string? designation { get; set; }
    }
}        

Similarly, your EmployeeDbContext.cs should look like this:

using Microsoft.EntityFrameworkCore;
namespace EmployeeCRUD.Models
{
    public class EmployeeDbContext : DbContext
    {
        public EmployeeDbContext(DbContextOptions options) : base(options)
        {
        }
        public DbSet<Employee> Employees { get; set; }
    }
}        

The EmployeeDbContext is derived from the class DbContext which is the part of Microsoft.EntityFrameworkCore package. In this class, we have established the context between the project and the SQL database and created the DbSet on the basis of which a table will be populated inside the database respectively.

Finally, create a new C# file inside the main project and name it EmployeeLogic.cs. The following class will be responsible for all the logic required to perform the CRUD operation and will be consumed by the Razor component respectively using Dependency Injection.

Your EmployeeLogic.cs should look like this:

using EmployeeCRUD.Models;
using Microsoft.EntityFrameworkCore;

namespace EmployeeCRUD
{
    public class EmployeeLogic
    {
        private readonly EmployeeDbContext _context;
        public EmployeeLogic(EmployeeDbContext context)
        {
            _context = context;
        }

        public async Task AddEmployee(Employee employee)
        {
            _context.Employees.Add(employee);
            await _context.SaveChangesAsync(); 
        }

        public async Task<Employee> GetEmployeeById(Guid id)
        {
            return await _context.Employees.FirstOrDefaultAsync(e => e.Id == id); 
        }

        public async Task UpdateEmployee(Employee employee)
        {
            _context.Employees.Update(employee);
            await _context.SaveChangesAsync(); 
        }

        public async Task DeleteEmployee(Guid id)
        {
            var employee = await GetEmployeeById(id);
            if (employee != null)
            {
                _context.Employees.Remove(employee);
                await _context.SaveChangesAsync();
            }
        }

        public async Task<List<Employee>> GetAllEmployees()
        {
            return await _context.Employees.ToListAsync(); 
        }
    }
}        

Establishing a connection between the SQL Database and project

Now that your project is initialized successfully, it's time to connect the project with your database. For that, navigate to your project's appsettings.json file and add the connection string. This connection string will establish the connection between the project and a database. You can get your connection string by navigating to the View ribbon bar from your VS 2022 and then SQL Server Object Explorer. When clicked, the explorer is opened at the right showing all the connections that you had previously. Add a new connection by clicking on the Add SQL Server button. You can retrieve your server name by navigating to your SQL server management studio.



Make sure that you trust the server certificate. Once done, the connection string will be automatically generated (as highlighted in the screenshot above). However, we have to modify the connection string a little as per the scenario.

Inside the appsettings.json, add the following code just below "AllowedHosts": "*",:

"ConnectionStrings": {
  "default": "Data Source=your-server-name;Initial Catalog=EmployeeDB;Integrated Security=True;Trust Server Certificate=True; MultipleActiveResultSets=True;"
}        

Once done, go to the project's Program.cs file and then add the following right below builder.Services.AddRazorComponents().AddInteractiveServerComponents();

builder.Services.AddDbContext<EmployeeDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("default")));
builder.Services.AddScoped<EmployeeLogic>();        

Finally, go to the Package Manager Console and run the following command and hit Enter:

Add-Migration "FirstMigration"        

The above command will create a migration in a distinguished folder. This migration consists of your database's context snapshot as well as the LINQ queries that generates the table accordingly.

Lastly, run the following command and you'll see that your database as well as the table is successfully made in the SQL Server.

Update-Database        
Your project should have the classes as shown

Creating an Employee form

Once the database is successfully connected, let's create a Razor component that will have the form through which employees detail will be added and modified respectively. First, go to Components > Layout > NavMenu.cs and add a link to another component similar to Home, Counter and Weather:

        <div class="nav-item px-3">
            <NavLink class="nav-link" href="employee">
                <span class="bi bi-list-nested-nav-menu" aria-hidden="true"></span> Employee
            </NavLink>
        </div>        

Now, create a new Razor Component inside the Pages folder, name it Employee.razor. The Employee.razor file should have the following:

@page "/employee"
@inject EmployeeLogic employeeLogic;
@rendermode InteractiveServer

<h3>Employee</h3>

<EditForm Model="employeeModel" OnSubmit="SaveEmployees" FormName="employeeForm">
    <div class="mb-3">
        <label for="name" class="form-label">Name</label>
        <InputText @bind-Value="employeeModel.Name" class="form-control" id="name"  />
    </div>
    <div class="mb-3">
        <label for="age" class="form-label">Age</label>
        <InputNumber @bind-Value="employeeModel.age" class="form-control" id="age"  />
    </div>
    <div class="mb-3">
        <label for="desig" class="form-label">Designation</label>
        <InputText @bind-Value="employeeModel.designation" class="form-control" id="desig"  />
    </div>

    <button type="submit" class="btn btn-primary">Submit</button>
</EditForm>

<table class="table table-bordered">
    <thead>
        <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Designation</th>
            <td>Delete</td>
        </tr>
    </thead>
    @foreach(var item in employeeList)
    {
        <tr>
            <td>@item.Name</td>
            <td>@item.age</td>
            <td>@item.designation</td>
            <td><button type="submit" @onclick="(()=>DeleteEmployee(item.Id))">Delete</button></td>
            <td><a href="employee/@item.Id">Update</a></td>
        </tr>
    }
    
</table>

@code {
    [SupplyParameterFromForm]
    private Models.Employee employeeModel { get; set; } = new Models.Employee();

    private List<Models.Employee> employeeList = new List<Models.Employee>();

    private async Task SaveEmployees()
    {
        await employeeLogic.AddEmployee(employeeModel);
        await GetEmployees();
        employeeModel = new Models.Employee();
    }

    private async Task GetEmployees()
    {
        employeeList = await employeeLogic.GetAllEmployees();
    }

    protected override async Task OnInitializedAsync()
    {
        await GetEmployees();
    }

    private async Task DeleteEmployee(Guid id)
    {
        await employeeLogic.DeleteEmployee(id);
        await GetEmployees();
    }
}        
The initial interface
The Employee interface

Whenever you will add something and click on Submit button, it will be shown on the same page's table.

SQL Database

Similarly you can perform the same for Update and Delete function.


Thanks for reading this article! I hope that it has enhanced your knowledge related to Microsoft .NET 8 and Entity Framework Core. ??



要查看或添加评论,请登录

Sameer Ahmed Siddiqui的更多文章

社区洞察

其他会员也浏览了