using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using UniversityContracts.BindingModels; using UniversityContracts.SearchModels; using UniversityContracts.StoragesContracts; using UniversityContracts.ViewModels; using UniversityDataBaseImplemet.Models; namespace UniversityDataBaseImplemet.Implements { public class EducationGroupStorage : IEducationGroupStorage { public EducationGroupViewModel? GetElement(EducationGroupSearchModel model) { if (!model.Id.HasValue) { return null; } using var context = new Database(); return context.EducationGroups .FirstOrDefault(record => record.Id == model.Id || record.Name.Equals(model.Name)) ?.GetViewModel; } public List GetFilteredList(EducationGroupSearchModel model) { using var context = new Database(); if (model.Id.HasValue) { return context.EducationGroups .Where(record => record.Id.Equals(model.Id)) .Select(record => record.GetViewModel) .ToList(); } else if (model.UserId.HasValue) { return context.EducationGroups .Where(record => record.UserId == model.UserId) .Select(record => record.GetViewModel) .ToList(); } else { return new(); } } public List GetFullList() { using var context = new Database(); return context.EducationGroups .Select(record => record.GetViewModel) .ToList(); } public EducationGroupViewModel? Insert(EducationGroupBindingModel model) { var newEducationGroup = EducationGroup.Create(model); if (newEducationGroup == null) { return null; } using var context = new Database(); context.EducationGroups.Add(newEducationGroup); context.SaveChanges(); return newEducationGroup.GetViewModel; } public EducationGroupViewModel? Update(EducationGroupBindingModel model) { using var context = new Database(); using var transaction = context.Database.BeginTransaction(); try { var educationgroup = context.EducationGroups .FirstOrDefault(record => record.Id.Equals(model.Id)); if (educationgroup == null) { return null; } educationgroup.Update(model); context.SaveChanges(); transaction.Commit(); return educationgroup.GetViewModel; } catch { transaction.Rollback(); throw; } } public int GetNumberOfPages(int userId, int pageSize) { using var context = new Database(); int carsCount = context.EducationGroups.Where(c => c.UserId == userId).Count(); int numberOfpages = (int)Math.Ceiling((double)carsCount / pageSize); return numberOfpages != 0 ? numberOfpages : 1; } public EducationGroupViewModel? Delete(EducationGroupBindingModel model) { using var context = new Database(); var educationgroup = context.EducationGroups .FirstOrDefault(record => record.Id.Equals(model.Id)); if (educationgroup == null) { return null; } context.EducationGroups.Remove(educationgroup); context.SaveChanges(); return educationgroup.GetViewModel; } } }