using SchoolAgainStudyContracts.BindingModel; using SchoolAgainStudyContracts.SearchModel; using SchoolAgainStudyContracts.StorageContracts; using SchoolAgainStudyContracts.ViewModel; using SchoolAgainStudyDataBaseImplements.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SchoolAgainStudyDataBaseImplements.Implements { public class MaterialStorage : IMaterialStorage { public List GetFullList() { using var context = new SchoolDataBase(); return context.Materials .Select(x => x.GetViewModel) .ToList(); } public List GetFilteredList(MaterialSearchModel model) { if (!model.TeacherId.HasValue) { return new(); } using var context = new SchoolDataBase(); return context.Materials .Where(x => x.TeacherId == model.TeacherId) .Select(x => x.GetViewModel) .ToList(); } public MaterialViewModel? GetElement(MaterialSearchModel model) { if (string.IsNullOrEmpty(model.Title) && !model.Id.HasValue && !model.TeacherId.HasValue) { return null; } using var context = new SchoolDataBase(); if(!string.IsNullOrEmpty(model.Title)&& model.TeacherId.HasValue) return context.Materials .FirstOrDefault(x => x.Title.Equals(model.Title) && x.TeacherId == model.TeacherId) ?.GetViewModel; return context.Materials .FirstOrDefault(x => x.Id == model.Id) ?.GetViewModel; } public MaterialViewModel? Insert(MaterialBindingModel model) { var newMaterial = Material.Create(model); if (newMaterial == null) { return null; } using var context = new SchoolDataBase(); context.Materials.Add(newMaterial); context.SaveChanges(); return newMaterial.GetViewModel; } public MaterialViewModel? Update(MaterialBindingModel model) { using var context = new SchoolDataBase(); var material = context.Materials.FirstOrDefault(x => x.Id == model.Id); if (material == null ) { return null; } material.Update(model); context.SaveChanges(); return material.GetViewModel; } public MaterialViewModel? Delete(MaterialBindingModel model) { using var context = new SchoolDataBase(); var element = context.Materials.FirstOrDefault(rec => rec.Id == model.Id); if (element != null ) { context.Materials.Remove(element); context.SaveChanges(); return element.GetViewModel; } return null; } } }