using SchoolContracts.BindingModels; using SchoolContracts.SearchModels; using SchoolContracts.StoragesContracts; using SchoolContracts.ViewModels; using SchoolDatabaseImplement.Models; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; using Microsoft.EntityFrameworkCore.Query; namespace SchoolDatabaseImplement.Implements { public class AccountStorage : IAccountStorage { private static IIncludableQueryable Accounts(SchoolDB context) => context.Accounts .Include(x => x.StudentByDiscipline).ThenInclude(x => x.Discipline) .Include(x => x.StudentByDiscipline).ThenInclude(x => x.Student); public List GetFullList() { using var context = new SchoolDB(); return Accounts(context) .Select(x => (AccountViewModel)x) .ToList(); } public List GetFilteredList(AccountSearchModel model) { if (model == null) { throw new ArgumentNullException(nameof(model), "Получена пустая поисковая модель"); } if (model.DateFrom.HasValue && !model.DateTo.HasValue || model.DateTo.HasValue && !model.DateFrom.HasValue) { throw new ArgumentException("Получена поисковая модель только с началом или концом периода"); } if (!model.DateFrom.HasValue && !model.StudentId.HasValue) { throw new ArgumentNullException(nameof(model.StudentId), "Получена поисковая модель без StudentId"); } if (!model.DateFrom.HasValue && !model.DisciplineId.HasValue) { throw new ArgumentNullException(nameof(model.DisciplineId), "Получена поисковая модель без DisciplineId"); } using var context = new SchoolDB(); if (model.DateFrom.HasValue) { return Accounts(context) .Where(x => model.DateFrom.Value <= x.DateOfAccount && x.DateOfAccount <= model.DateTo.Value) .Select(x => (AccountViewModel)x) .ToList(); } return Accounts(context) .Where(x => x.SchoolByDiscipline != null && x.SchoolByDiscipline.StudentId == model.StudentId && x.SchoolByDiscipline.DisciplineId == model.DisciplineId) .Select(x => (AccountViewModel)x) .ToList(); } public AccountViewModel? GetElement(AccountSearchModel model) { using var context = new SchoolDB(); return Accounts(context) .FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id)); } public AccountViewModel? Insert(AccountBindingModel model) { if (model == null) { return null; } var newAccount = Account.Create(model); using var context = new SchoolDB(); context.Accounts.Add(newAccount); context.SaveChanges(); return newAccount; } } }