Exploring CRUD Operations with ASP.NET Core Web API

GET Request: Retrieve Employee List

Use HTTP GET to fetch a list of employees.


[HttpGet]
public async Task Get()
{
var res = await _emp.GetEmpList();

var sanitizedUserList = res.Select(user => new EmployeeViewModelDTO
{
    EmpId = user.EmpId,
    FirstName = user.FirstName
}).ToList();
return Ok(sanitizedUserList);
}

POST Request: Add a New Employee

Use HTTP POST to add a new employee to the database.


[HttpPost]
public async Task Post(EmployeeDTO model)
{
try
{
    var result = await _emp.Post(model);   
    if (result > 0)
    {
        return Ok("Employee saved successfully.");
    }
    else
    {
        return BadRequest();
    }
}
catch(Exception)
{
    return StatusCode(500, "An internal server error occurred.");
}
}

PUT Request: Update an Employee

Use HTTP PUT to update an existing employee record.


[HttpPut("{id}")]
public async Task Update(int id, EmployeeDTO model)
{
try
{
    var result = await _emp.Update(model, id);
    if (result == "Employee updated successfully.")
    {
        return Ok(result);
    }
    else
    {
        return NotFound(result); // Employee not found
    }
}
catch (Exception ex)
{
    // Log the exception (ex) here if needed for debugging
    return StatusCode(500, "An internal server error occurred.");
}
}

DELETE Request: Delete an Employee

Use HTTP DELETE to remove an employee from the database.


[HttpDelete("{id}")]
public async Task Delete(int id)
{
try
{
    var result = await _emp.delete(id);
    if (result == "Employee deleted successfully.")
    {
        return Ok(result);
    }
    else
    {
        return NotFound(result); // Employee not found
    }
}
catch (Exception ex)
{
    // Log the exception (ex) here if needed for debugging
    return StatusCode(500, "An internal server error occurred.");
}
}

Interface Definition for Employee Controller

IEmployee Interface

Interface defining operations for managing employees.


using System.Collections.Generic;
using System.Threading.Tasks;

namespace jsonToken.Repo
{
public interface IEmployee
{
    Task<List<EmployeeDTO>> GetEmpList();
    Task<int> Post(EmployeeDTO model);
    Task<string> delete(int Id);
    Task<string> Update(EmployeeDTO model, int Id);
}
}

Employee Repository Implementation

Employees Class

Implementation of the `IEmployee` interface for managing employee data using Entity Framework Core.


using jsonToken.Data;
using jsonToken.model;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace jsonToken.Repo
{
public class Employees : IEmployee
{
    private TestContext _context;
    public Employees(TestContext context)
    {
        _context = context;
    }

    public async Task<string> delete(int Id)
    {
        // Fetch the existing employee
        var employee = await _context.Employees.FindAsync(Id);
        if (employee == null)
        {
            return "Employee not found.";
        }

        // Remove the employee from the database
        _context.Employees.Remove(employee);

        // Save the changes to the database
        await _context.SaveChangesAsync();

        return "Employee deleted successfully.";
    }

    public async Task<int> Post(EmployeeDTO model)
    {
        var employee = new Employee
        {
            EmpPassno = model.EmpPassno,
            FirstName = model.FirstName,
            LastName = model.LastName,
            Address = model.Address,
            DepartmentId = model.DepartmentId,
            RoleId = model.RoleId
        };

        _context.Employees.Add(employee);
        await _context.SaveChangesAsync();
        return employee.EmpId; // Assuming EmpId is generated by the database
    }

    public async Task<string> Update(EmployeeDTO model, int Id)
    {
        // Fetch the existing employee
        var employee = await _context.Employees.FindAsync(Id);
        if (employee == null)
        {
            return "Employee not found.";
        }

        // Update the employee properties with the values from the model
        employee.EmpPassno = model.EmpPassno;
        employee.FirstName = model.FirstName;
        employee.LastName = model.LastName;
        employee.Address = model.Address;
        employee.DepartmentId = model.DepartmentId;
        employee.RoleId = model.RoleId;

        // Save the changes to the database
        await _context.SaveChangesAsync();

        return "Employee updated successfully.";
    }

    async Task<List<EmployeeDTO>> IEmployee.GetEmpList()
    {
        List<EmployeeDTO> lstUser = new List<EmployeeDTO>();
        var res = await (from user in _context.Employees
                         select new EmployeeDTO
                         {
                             EmpId = user.EmpId,
                             FirstName = user.FirstName
                         }).ToListAsync();

        lstUser.AddRange(res);
        return lstUser;
    }
}
}

EmployeeDTO Model

EmployeeDTO Class

Data transfer object (DTO) for representing employee information.


namespace jsonToken.model
{
public class EmployeeDTO
{
    public int EmpId { get; set; }
    public string EmpPassno { get; set; } = null!;
    public string? FirstName { get; set; }
    public string? LastName { get; set; }
    public string? Address { get; set; }
    public int DepartmentId { get; set; }
    public int RoleId { get; set; }
}
}