public static IQueryable <LogViewModel> MapToViewModel(this IQueryable <Log> logs) => logs.Select(m => new LogViewModel { Id = m.Id, EmployeeId = m.EmployeeId, TimeIn = LogExtensions.ToLocal(m.TimeIn), TimeOut = (m.TimeOut == null) ? "": LogExtensions.ToLocal(m.TimeOut), Created = m.Created, Updated = m.Updated, Deleted = m.Deleted, FullName = m.Employee.FullName });
public async Task <LogResultViewModel> Handle(Command request, CancellationToken cancellationToken) { try { var newLog = new Log(); var log = await _context.Logs .Where(m => m.EmployeeId == request.ViewModel.Id) .Where(m => m.TimeOut == null) .Where(m => m.Deleted == null) .SingleOrDefaultAsync(cancellationToken); // Log in user if (log == null) { newLog.EmployeeId = request.ViewModel.Id; newLog.TimeIn = DateTime.UtcNow; await _context.Logs.AddAsync(newLog); } // Log out user else { var oldModel = await _context.Logs.FindAsync(log.Id); _mapper.Map(log, oldModel); oldModel.TimeOut = DateTime.UtcNow; _context.Entry(oldModel).State = EntityState.Modified; } // Save Insert/Update query await _context.SaveChangesAsync(); // Return result with employee information var result = (log != null) ? log : newLog; return(new LogResultViewModel { FullName = result.Employee.FullName, CardNo = request.ViewModel.CardNo, Position = request.ViewModel.Position, TimeIn = LogExtensions.ToLocal(result.TimeIn), TimeOut = (result.TimeOut != null) ? LogExtensions.ToLocal(result.TimeOut) : string.Empty }); } catch (Exception e) { Console.WriteLine(e); throw; } }
public async Task <LogViewModel> Handle(Command request, CancellationToken cancellationToken) { try { var model = await _context.Logs.FirstOrDefaultAsync(m => m.Id == request.ViewModel.Id); // Validate model if (model == null) { return(null); } // Convert datetime to UTC before updating request.ViewModel.TimeIn = LogExtensions.ToUtc(request.ViewModel.TimeIn.ToString()); request.ViewModel.TimeOut = (request.ViewModel.TimeOut != null) ? LogExtensions.ToUtc(request.ViewModel.TimeOut.ToString()) : request.ViewModel.TimeOut; // Update specifc fields only model.TimeIn = request.ViewModel.TimeIn; model.TimeOut = request.ViewModel.TimeOut; model.Updated = DateTime.UtcNow; _context.Entry(model).State = EntityState.Modified; await _context.SaveChangesAsync(); // Return result with log information return(await _context.Logs .Where(m => m.Id == model.Id) .MapToViewModel() .FirstAsync()); } catch (Exception e) { Console.WriteLine(e); throw; } }