CourseWork_SchoolStudyAgain/SchoolAgainStudy/SchoolAgainStudyDataBaseImplements/Implements/MaterialStorage.cs

90 lines
3.0 KiB
C#
Raw Normal View History

using SchoolAgainStudyContracts.BindingModel;
using SchoolAgainStudyContracts.SearchModel;
using SchoolAgainStudyContracts.StorageContracts;
using SchoolAgainStudyContracts.ViewModel;
using SchoolAgainStudyDataBaseImplements.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SchoolAgainStudyDataBaseImplements.Implements
{
public class MaterialStorage : IMaterialStorage
{
public List<MaterialViewModel> GetFullList()
{
using var context = new SchoolDataBase();
return context.Materials
.Select(x => x.GetViewModel)
.ToList();
}
public List<MaterialViewModel> GetFilteredList(MaterialSearchModel model)
{
if (!model.TeacherId.HasValue)
{
return new();
}
using var context = new SchoolDataBase();
return context.Materials
.Where(x => x.TeacherId == model.TeacherId)
.Select(x => x.GetViewModel)
.ToList();
}
public MaterialViewModel? GetElement(MaterialSearchModel model)
{
if ((string.IsNullOrEmpty(model.Title) && !model.Id.HasValue) || !model.TeacherId.HasValue)
{
return null;
}
using var context = new SchoolDataBase();
return context.Materials
.FirstOrDefault(x => ((!string.IsNullOrEmpty(model.Title) && x.Title == model.Title) ||
(model.Id.HasValue && x.Id == model.Id)) && x.TeacherId == model.TeacherId)
?.GetViewModel;
}
public MaterialViewModel? Insert(MaterialBindingModel model)
{
var newMaterial = Material.Create(model);
if (newMaterial == null)
{
return null;
}
using var context = new SchoolDataBase();
context.Materials.Add(newMaterial);
context.SaveChanges();
return newMaterial.GetViewModel;
}
public MaterialViewModel? Update(MaterialBindingModel model)
{
using var context = new SchoolDataBase();
var material = context.Materials.FirstOrDefault(x => x.Id == model.Id);
if (material == null )
{
return null;
}
material.Update(model);
context.SaveChanges();
return material.GetViewModel;
}
public MaterialViewModel? Delete(MaterialBindingModel model)
{
using var context = new SchoolDataBase();
var element = context.Materials.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null )
{
context.Materials.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}