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

83 lines
3.3 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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<Account, Student?> Accounts(SchoolDB context)
=> context.Accounts
.Include(x => x.StudentByDiscipline).ThenInclude(x => x.Discipline)
.Include(x => x.StudentByDiscipline).ThenInclude(x => x.Student);
public List<AccountViewModel> GetFullList()
{
using var context = new SchoolDB();
return Accounts(context)
.Select(x => (AccountViewModel)x)
.ToList();
}
public List<AccountViewModel> 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;
}
}
}