using Microsoft.EntityFrameworkCore; using ServiceStationContracts.BindingModels; using ServiceStationContracts.SearchModels; using ServiceStationContracts.ViewModels; using ServiceStationsContracts.StorageContracts; using ServiceStationsDataBaseImplement.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ServiceStationsDataBaseImplement.Implements { public class WorkStorage : IWorkStorage { public WorkViewModel? Insert(WorkBindingModel model) { using var context = new Database(); var newRec = Work.Create(context,model); if (newRec == null) { return null; } context.Works.Add(newRec); context.SaveChanges(); return newRec.GetViewModel; } public WorkViewModel? Update(WorkBindingModel model) { using var context = new Database(); using var transaction = context.Database.BeginTransaction(); try { var recUp = context.Works.FirstOrDefault(x => x.Id == model.Id); if (recUp == null) { return null; } recUp.Update(model); context.SaveChanges(); recUp.UpdateClients(context, model); transaction.Commit(); return recUp.GetViewModel; } catch { transaction.Rollback(); throw; } } public WorkViewModel? Delete(WorkBindingModel model) { using var context = new Database(); var recDel = context.Works .Include(x => x.WorkClients) .FirstOrDefault(rec => rec.Id == model.Id); if (recDel != null) { context.Works.Remove(recDel); context.SaveChanges(); return recDel.GetViewModel; } return null; } public WorkViewModel? GetElement(WorkSearchModel model) { using var context = new Database(); if (model.Id.HasValue) { return context.Works .Include(x => x.WorkClients) .ThenInclude(x => x._work) .FirstOrDefault(x => x.Id == model.Id) ?.GetViewModel; } else if (model.ExecutorId.HasValue) { return context.Works .Include(x => x.WorkClients) .ThenInclude(x => x._work) .FirstOrDefault(x => x.ExecutorId == model.ExecutorId) ?.GetViewModel; } return context.Works .Include(x => x.WorkClients) .ThenInclude(x => x._work) .FirstOrDefault(x => x.TaskId == model.TaskId) ?.GetViewModel; } public List GetFilteredList(WorkSearchModel model) { using var context = new Database(); if (model.DateFrom.HasValue && model.DateTo.HasValue) { return context.Works .Include(x => x.WorkClients) .ThenInclude(x => x._work) .Where(x => x.Date >= model.DateFrom && x.Date <= model.DateTo) .Select(x => x.GetViewModel) .ToList(); } else if (model.ExecutorId.HasValue) { return context.Works .Include(x => x.WorkClients) .ThenInclude(x => x._work) .Where(x => x.ExecutorId == model.ExecutorId) .Select(x => x.GetViewModel) .ToList(); } return context.Works .Include(x => x.WorkClients) .ThenInclude(x => x._work) .Where(x => x.TaskId == model.TaskId) .Select(x => x.GetViewModel) .ToList(); } public List GetFullList() { using var context = new Database(); return context.Works .Include(x => x.WorkClients) .ThenInclude(x => x._work) .Select(x => x.GetViewModel) .ToList(); } } }