using Microsoft.EntityFrameworkCore; 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 TeacherStorage : ITeacherStorage { public TeacherViewModel? Delete(TeacherBindingModel model) { using var context = new SchoolDataBase(); var element = context.Teachers .FirstOrDefault(rec => rec.Id == model.Id); if (element != null) { context.Teachers.Remove(element); context.SaveChanges(); return element.GetViewModel; } return null; } public TeacherViewModel? GetElement(TeacherSearchModel model) { if (string.IsNullOrEmpty(model.Login) && !model.Id.HasValue) { return null; } using var context = new SchoolDataBase(); return context.Teachers .FirstOrDefault(x => (!string.IsNullOrEmpty(model.Login) && x.Login == model.Login) || (model.Id.HasValue && x.Id == model.Id)) ?.GetViewModel; } public List GetFilteredList(TeacherSearchModel model) { if (string.IsNullOrEmpty(model.Name)) { return new(); } using var context = new SchoolDataBase(); return context.Teachers .Where(x => x.Name.Contains(model.Name)) .ToList() .Select(x => x.GetViewModel) .ToList(); } public List GetFullList() { using var context = new SchoolDataBase(); return context.Teachers .ToList() .Select(x => x.GetViewModel) .ToList(); } public TeacherViewModel? Insert(TeacherBindingModel model) { using var context = new SchoolDataBase(); var newTeacher = Teacher.Create(context, model); if (newTeacher == null) { return null; } context.Teachers.Add(newTeacher); context.SaveChanges(); return newTeacher.GetViewModel; } public TeacherViewModel? Update(TeacherBindingModel model) { using var context = new SchoolDataBase(); using var transaction = context.Database.BeginTransaction(); try { var teacher = context.Teachers.FirstOrDefault(rec => rec.Id == model.Id); if (teacher == null) { return null; } teacher.Update(model); context.SaveChanges(); transaction.Commit(); return teacher.GetViewModel; } catch { transaction.Rollback(); throw; } } } }