Home > front end >  How to Insert an "Employee Leave Application" into DB and update the last inserted record
How to Insert an "Employee Leave Application" into DB and update the last inserted record

Time:07-18

In my ASP.NET Core 6 Web API using Entity Framework, I am working on an Employee Leave Application.

And I have this model class:

public class EmployeeLeave
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }
    public virtual Employee Employee { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public LeaveType LeaveType { get; set; }
    public bool? IsCurrent { get; set; }
}

Then I also created some DTO as shown here:

public class LeaveRequestDto
{
    public Guid EmployeeId { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public LeaveType LeaveType { get; set; }
}

public class LeaveResponseDto
{
    public EmployeeResponseDto Employee { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public string LeaveType { get; set; }
    public bool? IsCurrent { get; set; }
}

Then I have the service for the implementation.

Interface:

Task<GenericResponseDto<LeaveResponseDto>> CreateAsync(LeaveRequestDto request);

Implementation:

public async Task<GenericResponseDto<LeaveResponseDto>> CreateAsync(LeaveRequestDto request)
{
    var response = new GenericResponseDto<LeaveResponseDto>();
    var employee = await _context.Employees.FirstOrDefaultAsync(e => e.Id == request.EmployeeId);

    if (employee == null)
    {
        response.Error = new ErrorResponseDto()
            {
                ErrorCode = 404,
                Message = "Employee does not exist in the system!"
            };
        response.StatusCode = 404;
    } 
    else
    {
        var leave = _mapper.Map<EmployeeLeave>(request);
        leave.Employee = employee;
        leave.IsCurrent = true;

        try
        {
            _context.EmployeeLeaves.Add(leave);
            await _context.SaveChangesAsync();
            response.Result = _mapper.Map<LeaveResponseDto>(leave);
            response.StatusCode = 201;
        }
        catch (Exception ex)
        {
            response.Error = new ErrorResponseDto()
                {
                    ErrorCode = 500,
                    Message = ex.Message
                };
            response.StatusCode = 500;
        }
    }

    return response;
}

Currently, what I have will insert a new record for the Employee Leave Application into the database.

What I want to achieve is that I want to keep all the records of the Leave Applications for each employee.

At the point of insert, the application should check the last leave application record of that particular employee, change isCurrent to false, and then insert a new record, and the new record will have isCurrent as true.

How do I achieve this?

Thanks

CodePudding user response:

You can retrieve the last record using LastOrDefault() and update it using EntityState.Modified

Try this

public async Task<GenericResponseDto<LeaveResponseDto>> CreateAsync(LeaveRequestDto request)
{
    var response = new GenericResponseDto<LeaveResponseDto>();
    var employee = await _context.Employees.FirstOrDefaultAsync(e => e.Id == request.EmployeeId);

    if (employee == null)
    {
        response.Error = new ErrorResponseDto()
            {
                ErrorCode = 404,
                Message = "Employee does not exist in the system!"
            };
        response.StatusCode = 404;
    } 
    else
    {
        var lastLeave = _context.Set<EmployeeLeave>().where(leave => 
        leave.Employee.Id == request.EmployeeId ).LastOrDefault();
        if(lastLeave != null)
        {
            lastLeave .IsCurrent = false;
            _context.Entry(lastLeave).State = EntityState.Modified;
        }
        var leave = _mapper.Map<EmployeeLeave>(request);
        leave.Employee = employee;
        leave.IsCurrent = true;


    try
        {
            _context.EmployeeLeaves.Add(leave);
            await _context.SaveChangesAsync();
            response.Result = _mapper.Map<LeaveResponseDto>(leave);
            response.StatusCode = 201;
        }
        catch (Exception ex)
        {
            response.Error = new ErrorResponseDto()
                {
                    ErrorCode = 500,
                    Message = ex.Message
                };
            response.StatusCode = 500;
        }
    }

    return response;
}
  • Related