ISEbd-22_CourseWork_School/School/SchoolDataBaseImplement/Implements/StudentStorage.cs

111 lines
3.9 KiB
C#
Raw Normal View History

2024-05-01 17:54:58 +04:00
using System.Security.Cryptography.X509Certificates;
using SchoolContracts.BindingModels;
using SchoolContracts.SearchModels;
using SchoolContracts.StoragesContracts;
using SchoolContracts.ViewModels;
using SchoolDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
namespace SchoolDatabaseImplement.Implements
{
public class StudentStorage : IStudentStorage
{
private void CheckSearchModel(StudentSearchModel model)
{
if (model == null)
throw new ArgumentNullException("Передаваемая модель для поиска равна нулю", nameof(model));
if (!model.Id.HasValue && !model.DirectorId.HasValue && model.DisciplinesIds == null)
throw new ArgumentException("Все передаваемые поля поисковой модели оказались пусты или равны null");
}
public StudentViewModel? Delete(StudentBindingModel model)
{
using var context = new SchoolDB();
var element = context.Students.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
context.Studentss.Remove(element);
context.SaveChanges();
return element;
}
return null;
}
public StudentViewModel? GetElement(StudentSearchModel model)
{
CheckSearchModel(model);
if (!model.Id.HasValue)
{
return null;
}
using var context = new SchoolDB();
return context.Students
.Include(x => x.Executor)
.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id);
}
public List<StudentViewModel> GetFilteredList(StudentSearchModel model)
{
CheckSearchModel(model);
if (model.Id.HasValue)
{
var res = GetElement(model);
return res != null ? new() { res } : new();
}
using var context = new SchoolDB();
var query = context.Students.Include(x => x.Executor);
if (model.DirectorId.HasValue)
{
return query
.Where(x => model.DirectorId == x.DirectorId)
.Select(x => (StudentViewModel)x)
.ToList();
}
if (model.DisciplinesIds != null)
return query
.Include(x => x.Disciplines)!
.ThenInclude(x => x.Discipline)
.ThenInclude(x => x.Student)
.Where(x => x.Disciplines.Any(y => model.DisciplinesIds.Contains(y.DisciplineId)))
.Select(x => (StudentViewModel)x)
.ToList();
return new();
}
public List<StudentViewModel> GetFullList()
{
using var context = new SchoolDB();
return context.Students.Include(x => x.Executor)
.Select(x => (StudentViewModel)x)
.ToList();
}
public StudentViewModel? Insert(StudentBindingModel model)
{
var newStudent = Student.Create(model);
if (newStudent == null)
{
return null;
}
using var context = new SchoolDB();
context.Students.Add(newStudent);
context.SaveChanges();
return newStudent;
}
public StudentViewModel? Update(StudentBindingModel model)
{
using var context = new SchoolDB();
var Student = context.Students.FirstOrDefault(x => x.Id == model.Id);
if (Student == null)
{
return null;
}
Student.Update(model);
context.SaveChanges();
return Student;
}
}
}