Tutorial - Employee Management System - Part 2

Employee Management System - Part 2: Building the ASP.NET Core RESTful API

EMS: Building the ASP.NET Core RESTful API

In this part, we will create an ASP.NET Core Web API project that will act as our RESTful service. This API will be responsible for interacting with the database using Entity Framework Core. This architecture allows us to keep our Blazor application independent of direct database access, making it easier to switch between Blazor Server and Blazor WebAssembly hosting models in the future.

Architecture Refresher:

Client (Blazor App) <---> RESTful Service (ASP.NET Core API) <---> Database (SQL Server via EF Core)

Step-by-Step Tutorial Guide (Part 2)

Part 2.1: Create ASP.NET Core REST API Project

  1. Add a New Project to the Solution:
    • Right-click on your BlazorTutorial solution in Solution Explorer.
    • Select "Add" -> "New Project...".
    • In the "Add a new project" window, search for "ASP.NET Core Web API" and select it. Click "Next".
    • Project name: EmployeeManagement.Api
    • Location: Ensure it's in the same solution directory.
    • Click "Next".
    • Framework: .NET 8.0 (Long Term Support) (or the latest stable LTS version).
    • Authentication type: "None".
    • Configure for HTTPS: Checked (recommended for production, though optional for local development).
    • Enable OpenAPI support: Checked (this is helpful for API documentation with Swagger/Swashbuckle).
    • Do not use top-level statements: Unchecked (we'll use top-level statements for Program.cs).
    • Click "Create".
  2. Add Project Reference to EmployeeManagement.Models:

    We need the Employee and Department model classes in our API project.

    • In the EmployeeManagement.Api project, right-click on "Dependencies", select "Add Project Reference...".
    • In the "Reference Manager" dialog, go to "Projects" -> "Solution".
    • Check the box next to EmployeeManagement.Models.
    • Click "OK".
  3. Update EmployeeManagement.Models.Employee Class:

    The Employee model in our EmployeeManagement.Models project needs a slight modification to better align with database storage where we'll typically store a DepartmentId rather than a direct Department object.

    • Open Employee.cs in the EmployeeManagement.Models project.
    • Remove the public Department Department { get; set; } line.
    • Add public int DepartmentId { get; set; }.
    • Your Employee.cs in the EmployeeManagement.Models project should now look like this:
  4. using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace EmployeeManagement.Models
    {
        public class Employee
        {
            public int EmployeeId { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string Email { get; set; }
            public DateTime DateOfBrith { get; set; }
            public Gender Gender { get; set; }
            public int DepartmentId { get; set; } // Added this line
            public string PhotoPath { get; set; }
        }
    }
    
    • Build the EmployeeManagement.Models project again to ensure changes are compiled.

Part 2.2: Setup Entity Framework Core DbContext

  1. Install Required NuGet Packages:
    • In Visual Studio, go to "Tools" -> "NuGet Package Manager" -> "Manage NuGet Packages for Solution...".
    • Select EmployeeManagement.Api project.
    • Go to the "Browse" tab.
    • Search for and install the following packages:
      • Microsoft.EntityFrameworkCore.SqlServer
      • Microsoft.EntityFrameworkCore.Tools
    • Ensure the latest stable versions are selected.
  2. Create Models Folder and AppDbContext.cs:
    • In the EmployeeManagement.Api project, right-click on the project name.
    • Select "Add" -> "New Folder". Name it Models.
    • Right-click on the newly created Models folder, select "Add" -> "Class...".
    • Name it AppDbContext.cs.
    • Replace its content with the following:
  3. using EmployeeManagement.Models; // Ensure this using statement is present
    using Microsoft.EntityFrameworkCore;
    using System;
    
    namespace EmployeeManagement.Api.Models
    {
        public class AppDbContext : DbContext
        {
            public AppDbContext(DbContextOptions<AppDbContext> options)
                : base(options)
            {
            }
    
            // DbSet properties for our entities
            public DbSet<Employee> Employees { get; set; }
            public DbSet<Department> Departments { get; set; }
    
            // Override OnModelCreating for data seeding
            protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
                base.OnModelCreating(modelBuilder);
    
                // Seed Departments Table
                modelBuilder.Entity<Department>().HasData(
                    new Department { DepartmentId = 1, DepartmentName = "IT" });
                modelBuilder.Entity<Department>().HasData(
                    new Department { DepartmentId = 2, DepartmentName = "HR" });
                modelBuilder.Entity<Department>().HasData(
                    new Department { DepartmentId = 3, DepartmentName = "Payroll" });
                modelBuilder.Entity<Department>().HasData(
                    new Department { DepartmentId = 4, DepartmentName = "Admin" });
    
                // Seed Employee Table
                modelBuilder.Entity<Employee>().HasData(new Employee
                {
                    EmployeeId = 1,
                    FirstName = "Raushan",
                    LastName = "Ranjan",
                    Email = "raushan@rrtech.com",
                    DateOfBrith = new DateTime(1980, 10, 5),
                    Gender = Gender.Male,
                    DepartmentId = 1, // Using DepartmentId now
                    PhotoPath = "images/raushan.jpg"
                });
    
                modelBuilder.Entity<Employee>().HasData(new Employee
                {
                    EmployeeId = 2,
                    FirstName = "Sam",
                    LastName = "Galloway",
                    Email = "Sam@rrtech.com",
                    DateOfBrith = new DateTime(1981, 12, 22),
                    Gender = Gender.Male,
                    DepartmentId = 2, // Using DepartmentId now
                    PhotoPath = "images/john.png" // Typo fixed: john.png
                });
    
                modelBuilder.Entity<Employee>().HasData(new Employee
                {
                    EmployeeId = 3,
                    FirstName = "Pratibha",
                    LastName = "Poddar",
                    Email = "pratibha@rrtech.com",
                    DateOfBrith = new DateTime(1979, 11, 11),
                    Gender = Gender.Female,
                    DepartmentId = 1, // Using DepartmentId now
                    PhotoPath = "images/pratibha.png"
                });
    
                modelBuilder.Entity<Employee>().HasData(new Employee
                {
                    EmployeeId = 4, // Corrected EmployeeId for uniqueness
                    FirstName = "Sara",
                    LastName = "Longway",
                    Email = "sara@rrtech.com",
                    DateOfBrith = new DateTime(1982, 9, 23),
                    Gender = Gender.Female,
                    DepartmentId = 3, // Using DepartmentId now
                    PhotoPath = "images/sara.png" // Typo fixed: mary.png or another if available
                });
            }
        }
    }
    
    • Note: I've corrected PhotoPath for e2 to images/john.png (assuming that's the image you have) and e4 to images/sara.png for consistency, but ensure these match your actual image filenames. The original text had john.png in the EmployeeListBase.cs so sticking to that.

Part 2.3: Configure Program.cs for Database Connection

  1. Add Database Connection String:
    • Open appsettings.json in the EmployeeManagement.Api project.
    • Add the ConnectionStrings section as shown below. Place it typically at the top level, alongside Logging and AllowedHosts.
  2. {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft.AspNetCore": "Warning"
        }
      },
      "AllowedHosts": "*",
      "ConnectionStrings": {
        "DBConnection": "server=(localdb)\\MSSQLLocalDB;database=EmployeeDB;Trusted_Connection=true;MultipleActiveResultSets=true"
      }
    }
    
    • Note on MultipleActiveResultSets=true: This is often useful with Entity Framework, especially when loading related data. I've added it as a common practice.
  3. Configure Services in Program.cs:
    • Open Program.cs in the EmployeeManagement.Api project.
    • Add necessary using statements at the top:
  4. using EmployeeManagement.Api.Models; // For AppDbContext
    using Microsoft.EntityFrameworkCore;   // For UseSqlServer extension method
    
    var builder = WebApplication.CreateBuilder(args);
    
    // Add services to the container.
    builder.Services.AddControllers();
    // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen();
    
    // Add AppDbContext to the services container
    builder.Services.AddDbContext<AppDbContext>(options =>
        options.UseSqlServer(builder.Configuration.GetConnectionString("DBConnection")));
    
    var app = builder.Build();
    // ... rest of the file
    
    • Add the DbContext to the services container using the connection string from appsettings.json. Place this code within the "Add services to the container" section, typically after builder.Services.AddControllers() or builder.Services.AddEndpointsApiExplorer().

Part 2.4: Create and Execute Database Migrations

  1. Open Package Manager Console:
    • In Visual Studio, go to "Tools" -> "NuGet Package Manager" -> "Package Manager Console".
  2. Set Default Project:
    • In the Package Manager Console, ensure that EmployeeManagement.Api is selected as the "Default project" in the dropdown menu.
  3. Add Initial Migration:
    • Type the following command and press Enter:
  4. Add-Migration InitialCreate
    
    • This command will create a Migrations folder in your EmployeeManagement.Api project, containing a timestamped C# file that defines the database schema and the data seeding operations based on your AppDbContext.
  5. Update Database:
    • After the migration file is generated, type the following command and press Enter:
  6. Update-Database
    
    • This command will create the EmployeeDB database (if it doesn't exist) on your local SQL Server instance ((localdb)\MSSQLLocalDB), create the Employees and Departments tables, and seed them with the data you defined in AppDbContext.cs.
    • You can verify the database creation and data by connecting to (localdb)\MSSQLLocalDB using SQL Server Object Explorer in Visual Studio or SQL Server Management Studio (SSMS).

You have now successfully set up your ASP.NET Core REST API project, configured Entity Framework Core, and created your database with initial seeded data. The next steps would involve implementing the actual API controllers to expose the employee data via HTTP endpoints.

Comments

Popular posts from this blog

Blazor: Building Web Apps with C# - Introduction

Blazor WebAssembly Hosted App Tutorial: Envelope Tracker System

Securing MVC-based Applications Using Blazor