using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TaskTrackerContracts.BindingModels; using TaskTrackerContracts.SearchModels; using TaskTrackerContracts.StoragesContracts; using TaskTrackerContracts.ViewModels; using TaskTrackerDatabase.Models; namespace TaskTrackerDatabase.Implements { public class OrganizationStorage : IOrganizationStorage { public List GetFullList() { using var context = new TaskTrackerDatabase(); return context.Organizations .Include(x => x.Projects) .ThenInclude(x => x.Project) .ToList() .Select(x => x.GetViewModel) .ToList(); } public List GetFilteredList(OrganizationSearchModel model) { if (string.IsNullOrEmpty(model.OrganizationName)) { return new(); } using var context = new TaskTrackerDatabase(); return context.Organizations .Include(x => x.Projects) .ThenInclude(x => x.Project) .Where(x => x.OrganizationName.Contains(model.OrganizationName)) .ToList() .Select(x => x.GetViewModel) .ToList(); } public OrganizationViewModel? GetElement(OrganizationSearchModel model) { if (string.IsNullOrEmpty(model.OrganizationName) && !model.Id.HasValue) { return null; } using var context = new TaskTrackerDatabase(); return context.Organizations .Include(x => x.Projects) .ThenInclude(x => x.Project) .FirstOrDefault(x => (!string.IsNullOrEmpty(model.OrganizationName) && x.OrganizationName == model.OrganizationName) || (model.Id.HasValue && x.Id == model.Id)) ?.GetViewModel; } public OrganizationViewModel? Insert(OrganizationBindingModel model) { using var context = new TaskTrackerDatabase(); var newReinforced = Organization.Create(context, model); if (newReinforced == null) { return null; } context.Organizations.Add(newReinforced); context.SaveChanges(); return newReinforced.GetViewModel; } public OrganizationViewModel? Update(OrganizationBindingModel model) { using var context = new TaskTrackerDatabase(); using var transaction = context.Database.BeginTransaction(); try { var reinforced = context.Organizations.FirstOrDefault(rec => rec.Id == model.Id); if (reinforced == null) { return null; } reinforced.Update(model); context.SaveChanges(); reinforced.UpdateProjects(context, model); transaction.Commit(); return reinforced.GetViewModel; } catch { transaction.Rollback(); throw; } } public OrganizationViewModel? Delete(OrganizationBindingModel model) { using var context = new TaskTrackerDatabase(); var element = context.Organizations .Include(x => x.Projects) .FirstOrDefault(rec => rec.Id == model.Id); if (element != null) { context.Organizations.Remove(element); context.SaveChanges(); return element.GetViewModel; } return null; } } }