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.Runtime.ConstrainedExecution; using System.Text; using System.Threading.Tasks; namespace SchoolAgainStudyDataBaseImplements.Implements { public class StudentStorage : IStudentStorage { public StudentViewModel? Delete(StudentBindingModel model) { using var context = new SchoolDataBase(); var element = context.Students .FirstOrDefault(rec => rec.Id == model.Id); if (element != null) { context.Students.Remove(element); context.SaveChanges(); return element.GetViewModel; } return null; } public StudentViewModel? GetElement(StudentSearchModel model) { if (string.IsNullOrEmpty(model.Login) && !model.Id.HasValue) { return null; } using var context = new SchoolDataBase(); return context.Students .FirstOrDefault(x => (!string.IsNullOrEmpty(model.Login) && x.Login == model.Login) || (model.Id.HasValue && x.Id == model.Id)) ?.GetViewModel; } public List GetFilteredList(StudentSearchModel model) { if (string.IsNullOrEmpty(model.Name)) { return new(); } using var context = new SchoolDataBase(); return context.Students .Where(x => x.Name.Contains(model.Name)) .ToList() .Select(x => x.GetViewModel) .ToList(); } public List GetFullList() { using var context = new SchoolDataBase(); return context.Students .ToList() .Select(x => x.GetViewModel) .ToList(); } public StudentViewModel? Insert(StudentBindingModel model) { using var context = new SchoolDataBase(); var newStudent = Student.Create(context, model); if (newStudent == null) { return null; } context.Students.Add(newStudent); context.SaveChanges(); return newStudent.GetViewModel; } public StudentViewModel? Update(StudentBindingModel model) { using var context = new SchoolDataBase(); using var transaction = context.Database.BeginTransaction(); try { var student = context.Students.FirstOrDefault(rec => rec.Id == model.Id); if (student == null) { return null; } student.Update(model); context.SaveChanges(); transaction.Commit(); return student.GetViewModel; } catch { transaction.Rollback(); throw; } } } }