SUBD-Petrushin-Egor-PIbd-22/TaskTrackerDatabase/Implements/StudentStorage.cs
2024-05-14 20:26:30 +04:00

88 lines
2.8 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TaskTrackerContracts.BindingModels;
using TaskTrackerContracts.SearchModels;
using TaskTrackerContracts.StoragesContracts;
using TaskTrackerContracts.ViewModels;
using TaskTrackerDatabase.Models;
namespace TaskTrackerDatabase.Implements
{
public class StudentStorage : IStudentStorage
{
public List<StudentViewModel> GetFullList()
{
using var context = new TaskTrackerDatabase();
return context.Students
.Select(x => x.GetViewModel)
.ToList();
}
public List<StudentViewModel> GetFilteredList(StudentSearchModel model)
{
if (string.IsNullOrEmpty(model.Name))
{
return new();
}
using var context = new TaskTrackerDatabase();
return context.Students
.Where(x => x.Name.Contains(model.Name))
.Select(x => x.GetViewModel)
.ToList();
}
public StudentViewModel? GetElement(StudentSearchModel model)
{
if (string.IsNullOrEmpty(model.Name) && !model.Id.HasValue)
{
return null;
}
using var context = new TaskTrackerDatabase();
return context.Students.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.Name) && x.Name == model.Name || (model.Id.HasValue && x.Id == model.Id)))?.GetViewModel;
}
public StudentViewModel? Insert(StudentBindingModel model)
{
var newStudent = Student.Create(model);
if (newStudent == null)
{
return null;
}
using var context = new TaskTrackerDatabase();
context.Students.Add(newStudent);
context.SaveChanges();
return newStudent.GetViewModel;
}
public StudentViewModel? Update(StudentBindingModel model)
{
using var context = new TaskTrackerDatabase();
var user = context.Students.FirstOrDefault(x => x.Id == model.Id);
if (user == null)
{
return null;
}
user.Update(model);
context.SaveChanges();
return user.GetViewModel;
}
public StudentViewModel? Delete(StudentBindingModel model)
{
using var context = new TaskTrackerDatabase();
var element = context.Students.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
context.Students.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}