ISEbd-21_Tukaeva_A_A_School/School/SchoolDatabaseImplements/Implements/LessonStorage.cs

90 lines
2.4 KiB
C#
Raw Normal View History

using Microsoft.EntityFrameworkCore;
using SchoolContracts.BindingModel;
using SchoolContracts.SearchModel;
using SchoolContracts.StoragesContracts;
using SchoolContracts.ViewModels;
using SchoolDatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SchoolDatabaseImplement.Implements
{
public class LessonStorage : ILessonStorage
{
public List<LessonViewModel> GetFullList()
{
using var context = new SchoolDatabase();
return context.Lessons
.Include (x => x.Employee)
.Select(x => x.GetViewModel)
.ToList();
}
public List<LessonViewModel> GetFilteredList(LessonSearchModel model)
{
using var context = new SchoolDatabase();
return context.Lessons
.Where(x => x.Id == model.Id)
.Include(x => x.Employee)
.Select(x => x.GetViewModel)
.ToList();
}
public LessonViewModel? GetElement(LessonSearchModel model)
{
using var context = new SchoolDatabase();
if (model.Id.HasValue)//сначала ищем по Id
{
return context.Lessons
.Include(x => x.Employee)
.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
}
if (!string.IsNullOrEmpty(model.LessonName))//затем по названию
{
return context.Lessons
.Include(x => x.Employee)
.FirstOrDefault(x => x.LessonName == model.LessonName)?.GetViewModel;
}
return null;
}
public LessonViewModel? Insert(LessonBindingModel model)
{
using var context = new SchoolDatabase();
var newLesson = Lesson.Create(context, model);
if (newLesson == null)
{
return null;
}
context.Lessons.Add(newLesson);
context.SaveChanges();
return newLesson.GetViewModel;
}
public LessonViewModel? Update(LessonBindingModel model)
{
using var context = new SchoolDatabase();
var lesson = context.Lessons.FirstOrDefault(x => x.Id == model.Id);
if (lesson == null)
{
return null;
}
lesson.Update(model);
context.SaveChanges();
return lesson.GetViewModel;
}
public LessonViewModel? Delete(LessonBindingModel model)
{
using var context = new SchoolDatabase();
var element = context.Lessons.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
context.Lessons.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}