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

98 lines
2.6 KiB
C#

using SchoolContracts.BindingModel;
using SchoolContracts.SearchModel;
using SchoolContracts.StoragesContracts;
using SchoolContracts.ViewModels;
using SchoolDatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SchoolDatabaseImplement.Implements
{
public class ClientStorage : IClientStorage
{
public List<ClientViewModel> GetFullList()
{
using var context = new SchoolDatabase();
return context.Clients
.Select(x => x.GetViewModel)
.ToList();
}
public List<ClientViewModel> GetFilteredList(ClientSearchModel model)
{
if (model == null)
{
return new();
}
if (model.Id.HasValue)
{
var res = GetElement(model);
return res != null ? new() { res } : new();
}
if (model.ClientEmail != null)
{
using var context = new SchoolDatabase();
return context.Clients
.Where(rec => rec.ClientEmail.Contains(model.ClientEmail))
.Select(x => x.GetViewModel)
.ToList();
}
return new();
}
public ClientViewModel? GetElement(ClientSearchModel model)
{
if (model == null)
{
return null;
}
using var context = new SchoolDatabase();
if (model.Id.HasValue)
return context.Clients.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
if (model.ClientEmail != null && model.ClientPassword != null)
return context.Clients
.FirstOrDefault(x => x.ClientEmail == model.ClientEmail
&& x.ClientPassword == model.ClientPassword)?.GetViewModel;
if (model.ClientEmail != null)
return context.Clients.FirstOrDefault(x => x.ClientEmail == model.ClientEmail)?.GetViewModel;
return null;
}
public ClientViewModel? Insert(ClientBindingModel model)
{
using var context = new SchoolDatabase();
if(model == null)
{
return null;
}
var newClient = Client.Create(model);
if(newClient == null)
{
return null;
}
context.Clients.Add(newClient);
context.SaveChanges();
return newClient.GetViewModel();
}
public ClientViewModel? Update(ClientBindingModel model)
{
using var context = new SchoolDatabase();
var res = context.Clients.FirstOrDefault(x => x.Id == model.Id);
res?.Update(model);
context.SaveChanges();
return res?.GetViewModel;
}
public ClientViewModel? Delete(ClientBindingModel model)
{
using var context = new SchoolDatabase();
var res = context.Clients.FirstOrDefault(x => x.Id == model.Id);
if (res != null)
{
context.Clients.Remove(res);
context.SaveChanges();
}
return res?.GetViewModel;
}
}
}