SUBD_SchoolSchedule/SchoolSchedule/SchoolScheduleDataBaseImplement/Implements/StudentStorage.cs
2024-04-08 22:02:19 +04:00

103 lines
2.8 KiB
C#

using Microsoft.EntityFrameworkCore;
using SchoolScheduleContracts.BindingModels;
using SchoolScheduleContracts.BusinessLogicsContracts;
using SchoolScheduleContracts.SearchModels;
using SchoolScheduleContracts.StoragesContracts;
using SchoolScheduleContracts.ViewModels;
using SchoolScheduleDataBaseImplement.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SchoolScheduleDataBaseImplement.Implements
{
public class StudentStorage : IStudentStorage
{
public List<StudentViewModel> GetFullList()
{
using var context = new SchoolScheduleDataBase();
return context.Students.Include(x => x.Grade)
.Select(x => x.GetViewModel)
.ToList();
}
public List<StudentViewModel> GetFilteredList(StudentSearchModel model)
{
using var context = new SchoolScheduleDataBase();
return context.Students.Include(x => x.Grade)
.Where(x => (!model.Id.HasValue || x.Id == model.Id) && (string.IsNullOrEmpty(model.FullName) || x.FullName == model.FullName)
&& (!model.GradeId.HasValue || x.GradeId == model.GradeId))
.Select(x => x.GetViewModel)
.ToList();
}
public StudentViewModel? GetElement(StudentSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new SchoolScheduleDataBase();
return context.Students.Include(x => x.Grade)
.FirstOrDefault(x =>
(model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public StudentViewModel? Insert(StudentBindingModel model)
{
using var context = new SchoolScheduleDataBase();
var newComponent = Student.Create(context, model);
if (newComponent == null)
{
return null;
}
context.Students.Add(newComponent);
context.SaveChanges();
return newComponent.GetViewModel;
}
public StudentViewModel? Update(StudentBindingModel model)
{
using var context = new SchoolScheduleDataBase();
using var transaction = context.Database.BeginTransaction();
try
{
var component = context.Students.FirstOrDefault(x => x.Id ==
model.Id);
if (component == null)
{
return null;
}
if (component == null)
{
return null;
}
component.Update(context, model);
context.SaveChanges();
component.UpdateAttendance(context, model);
transaction.Commit();
return component.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
}
}
public StudentViewModel? Delete(StudentBindingModel model)
{
using var context = new SchoolScheduleDataBase();
var element = context.Students.FirstOrDefault(rec => rec.Id ==
model.Id);
if (element != null)
{
context.Students.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}