Tutorial - Employee Management System - Part 2
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
- Add a New Project to the Solution:
- Right-click on your
BlazorTutorialsolution 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".
- Right-click on your
- Add Project Reference to EmployeeManagement.Models:
We need the
EmployeeandDepartmentmodel classes in our API project.- In the
EmployeeManagement.Apiproject, 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".
- In the
- Update EmployeeManagement.Models.Employee Class:
The
Employeemodel in ourEmployeeManagement.Modelsproject needs a slight modification to better align with database storage where we'll typically store aDepartmentIdrather than a directDepartmentobject.- Open
Employee.csin theEmployeeManagement.Modelsproject. - Remove the
public Department Department { get; set; }line. - Add
public int DepartmentId { get; set; }. - Your
Employee.csin theEmployeeManagement.Modelsproject should now look like this:
- Open
- Build the
EmployeeManagement.Modelsproject again to ensure changes are compiled.
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; } } }
Part 2.2: Setup Entity Framework Core DbContext
- Install Required NuGet Packages:
- In Visual Studio, go to "Tools" -> "NuGet Package Manager" -> "Manage NuGet Packages for Solution...".
- Select
EmployeeManagement.Apiproject. - Go to the "Browse" tab.
- Search for and install the following packages:
Microsoft.EntityFrameworkCore.SqlServerMicrosoft.EntityFrameworkCore.Tools
- Ensure the latest stable versions are selected.
- Create Models Folder and AppDbContext.cs:
- In the
EmployeeManagement.Apiproject, right-click on the project name. - Select "Add" -> "New Folder". Name it
Models. - Right-click on the newly created
Modelsfolder, select "Add" -> "Class...". - Name it
AppDbContext.cs. - Replace its content with the following:
- In the
- Note: I've corrected PhotoPath for e2 to
images/john.png(assuming that's the image you have) and e4 toimages/sara.pngfor consistency, but ensure these match your actual image filenames. The original text hadjohn.pngin theEmployeeListBase.csso sticking to that.
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 }); } } }
Part 2.3: Configure Program.cs for Database Connection
- Add Database Connection String:
- Open
appsettings.jsonin theEmployeeManagement.Apiproject. - Add the
ConnectionStringssection as shown below. Place it typically at the top level, alongsideLoggingandAllowedHosts.
- Open
- Note on
MultipleActiveResultSets=true: This is often useful with Entity Framework, especially when loading related data. I've added it as a common practice. - Configure Services in Program.cs:
- Open
Program.csin theEmployeeManagement.Apiproject. - Add necessary
usingstatements at the top:
- Open
- 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 afterbuilder.Services.AddControllers()orbuilder.Services.AddEndpointsApiExplorer().
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DBConnection": "server=(localdb)\\MSSQLLocalDB;database=EmployeeDB;Trusted_Connection=true;MultipleActiveResultSets=true"
}
}
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
Part 2.4: Create and Execute Database Migrations
- Open Package Manager Console:
- In Visual Studio, go to "Tools" -> "NuGet Package Manager" -> "Package Manager Console".
- Set Default Project:
- In the Package Manager Console, ensure that
EmployeeManagement.Apiis selected as the "Default project" in the dropdown menu.
- In the Package Manager Console, ensure that
- Add Initial Migration:
- Type the following command and press Enter:
- This command will create a
Migrationsfolder in yourEmployeeManagement.Apiproject, containing a timestamped C# file that defines the database schema and the data seeding operations based on yourAppDbContext. - Update Database:
- After the migration file is generated, type the following command and press Enter:
- This command will create the
EmployeeDBdatabase (if it doesn't exist) on your local SQL Server instance ((localdb)\MSSQLLocalDB), create theEmployeesandDepartmentstables, and seed them with the data you defined inAppDbContext.cs. - You can verify the database creation and data by connecting to
(localdb)\MSSQLLocalDBusing SQL Server Object Explorer in Visual Studio or SQL Server Management Studio (SSMS).
Add-Migration InitialCreate
Update-Database
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
Post a Comment