shoc-backend/SeaHaven.DataServices/Implementation/EmployeeDataService.cs
2026-04-28 18:55:14 -05:00

92 lines
2.7 KiB
C#

using Data.SeaHavenIndustries;
using Microsoft.EntityFrameworkCore;
using SeaHaven.DataServices.Interfaces;
namespace SeaHaven.DataServices.Implementation
{
public class EmployeeDataService : IEmployeeDataService
{
private readonly ApplicationDbContext _context;
public EmployeeDataService(ApplicationDbContext context)
{
_context = context;
}
public async Task<Employee?> GetByIdAsync(int id)
{
return await _context.Employees.FindAsync(id);
}
public async Task<Employee?> GetByIdWithDetailsAsync(int id)
{
return await _context.Employees
.Include(e => e.Department)
.Include(e => e.JobTitle)
.Include(e => e.Emails)
.FirstOrDefaultAsync(e => e.Id == id);
}
public async Task<IEnumerable<Employee>> GetAllAsync()
{
return await _context.Employees.ToListAsync();
}
public async Task<(IEnumerable<Employee> Items, int TotalCount)> GetPagedAsync(
int page,
int pageSize,
string? search = null)
{
var query = _context.Employees.AsQueryable();
if (!string.IsNullOrWhiteSpace(search))
{
query = query.Where(e => (e.FirstName + " " + e.LastName).Contains(search));
}
var totalCount = await query.CountAsync();
var items = await query
.OrderBy(e => e.LastName)
.Skip((page - 1) * pageSize)
.Take(pageSize)
.ToListAsync();
return (items, totalCount);
}
public async Task<Employee> AddAsync(Employee employee)
{
employee.CreatedDate = DateTime.Now;
await _context.Employees.AddAsync(employee);
await _context.SaveChangesAsync();
return employee;
}
public async Task UpdateAsync(Employee employee)
{
employee.LastModificationTime = DateTime.Now;
_context.Employees.Update(employee);
await _context.SaveChangesAsync();
}
public async Task DeleteAsync(int id)
{
var entity = await GetByIdAsync(id);
if (entity != null)
{
_context.Employees.Remove(entity);
await _context.SaveChangesAsync();
}
}
public async Task<bool> ExistsAsync(int id)
{
return await _context.Employees.AnyAsync(e => e.Id == id);
}
public async Task<int> CountAsync()
{
return await _context.Employees.CountAsync();
}
}
}