Overview
This article guides you through creating a simple Employee Management System with CRUD functionality using.
- Backend: ASP.NET Core Web API
- Frontend: React.js
- Database: SQL Server (via Entity Framework Core)
Step 1. Backend Setup - ASP.NET Core Web API
1.1. Create Project
Run this command on bash.
dotnet new webapi -n EmployeeAPI
cd EmployeeAPI
1.2. Add EF Core Packages
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
1.3. Create Employee Model
// Models/Employee.cs
namespace EmployeeAPI.Models
{
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Department { get; set; }
public decimal Salary { get; set; }
}
}
1.4. Create DbContext
// Data/EmployeeContext.cs
using Microsoft.EntityFrameworkCore;
using EmployeeAPI.Models;
namespace EmployeeAPI.Data
{
public class EmployeeContext : DbContext
{
public EmployeeContext(DbContextOptions<EmployeeContext> options)
: base(options)
{
}
public DbSet<Employee> Employees { get; set; }
}
}
1.5. Register DbContext in Program.cs
builder.Services.AddDbContext<EmployeeContext>(options =>
options.UseSqlServer(
builder.Configuration.GetConnectionString("DefaultConnection")
)
);
1.6. Add Connection String to appsettings.json
"ConnectionStrings": {
"DefaultConnection": "Server=YOUR_SERVER;Database=EmployeeDb;Trusted_Connection=True;"
}
using Microsoft.AspNetCore.Mvc;
using EmployeeAPI.Data;
using EmployeeAPI.Models;
using Microsoft.EntityFrameworkCore;
[ApiController]
[Route("api/[controller]")]
public class EmployeesController : ControllerBase
{
private readonly EmployeeContext _context;
public EmployeesController(EmployeeContext context) => _context = context;
[HttpGet]
public async Task<ActionResult<IEnumerable<Employee>>> GetEmployees() =>
await _context.Employees.ToListAsync();
[HttpGet("{id}")]
public async Task<ActionResult<Employee>> GetEmployee(int id)
{
var emp = await _context.Employees.FindAsync(id);
return emp == null ? NotFound() : emp;
}
[HttpPost]
public async Task<ActionResult<Employee>> CreateEmployee(Employee emp)
{
_context.Employees.Add(emp);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetEmployee), new { id = emp.Id }, emp);
}
[HttpPut("{id}")]
public async Task<IActionResult> UpdateEmployee(int id, Employee emp)
{
if (id != emp.Id)
return BadRequest();
_context.Entry(emp).State = EntityState.Modified;
await _context.SaveChangesAsync();
return NoContent();
}
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteEmployee(int id)
{
var emp = await _context.Employees.FindAsync(id);
if (emp == null)
return NotFound();
_context.Employees.Remove(emp);
await _context.SaveChangesAsync();
return NoContent();
}
}
Join the conversation! Your thoughts help the community grow.