107 lines
3.5 KiB
C#
107 lines
3.5 KiB
C#
using Microsoft.EntityFrameworkCore;
|
|
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 TeacherStorage : ITeacherStorage
|
|
{
|
|
public TeacherViewModel? Delete(TeacherBindingModel model)
|
|
{
|
|
using var context = new SchoolDataBase();
|
|
var element = context.Teachers
|
|
.FirstOrDefault(rec => rec.Id == model.Id);
|
|
if (element != null)
|
|
{
|
|
context.Teachers.Remove(element);
|
|
context.SaveChanges();
|
|
return element.GetViewModel;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
public TeacherViewModel? GetElement(TeacherSearchModel model)
|
|
{
|
|
if (string.IsNullOrEmpty(model.Login) && !model.Id.HasValue && string.IsNullOrEmpty(model.Password))
|
|
{
|
|
return null;
|
|
}
|
|
using var context = new SchoolDataBase();
|
|
if(!string.IsNullOrEmpty(model.Login)&&!string.IsNullOrEmpty(model.Password))
|
|
return context.Teachers
|
|
.FirstOrDefault(x => x.Login.Equals(model.Login)&& x.Password.Equals(model.Password))
|
|
?.GetViewModel;
|
|
return context.Teachers
|
|
.FirstOrDefault(x => x.Id == model.Id)
|
|
?.GetViewModel;
|
|
}
|
|
|
|
public List<TeacherViewModel> GetFilteredList(TeacherSearchModel model)
|
|
{
|
|
if (string.IsNullOrEmpty(model.Name))
|
|
{
|
|
return new();
|
|
}
|
|
using var context = new SchoolDataBase();
|
|
return context.Teachers
|
|
.Where(x => x.Name.Contains(model.Name))
|
|
.ToList()
|
|
.Select(x => x.GetViewModel)
|
|
.ToList();
|
|
}
|
|
|
|
public List<TeacherViewModel> GetFullList()
|
|
{
|
|
using var context = new SchoolDataBase();
|
|
return context.Teachers
|
|
.ToList()
|
|
.Select(x => x.GetViewModel)
|
|
.ToList();
|
|
}
|
|
|
|
public TeacherViewModel? Insert(TeacherBindingModel model)
|
|
{
|
|
using var context = new SchoolDataBase();
|
|
var newTeacher = Teacher.Create(context, model);
|
|
if (newTeacher == null)
|
|
{
|
|
return null;
|
|
}
|
|
context.Teachers.Add(newTeacher);
|
|
context.SaveChanges();
|
|
return newTeacher.GetViewModel;
|
|
}
|
|
|
|
public TeacherViewModel? Update(TeacherBindingModel model)
|
|
{
|
|
using var context = new SchoolDataBase();
|
|
using var transaction = context.Database.BeginTransaction();
|
|
try
|
|
{
|
|
var teacher = context.Teachers.FirstOrDefault(rec => rec.Id == model.Id);
|
|
if (teacher == null)
|
|
{
|
|
return null;
|
|
}
|
|
teacher.Update(model);
|
|
context.SaveChanges();
|
|
transaction.Commit();
|
|
return teacher.GetViewModel;
|
|
}
|
|
catch
|
|
{
|
|
transaction.Rollback();
|
|
throw;
|
|
}
|
|
}
|
|
}
|
|
}
|