PIbd-21_BatylkinaAO_MusoevD.../Canteen/CanteenDatabaseImplement/Implements/ManagerStorage.cs
2023-04-09 00:34:25 +04:00

98 lines
2.8 KiB
C#

using CanteenContracts.BindingModels;
using CanteenContracts.SearchModel;
using CanteenContracts.StoragesContracts;
using CanteenContracts.View;
using CanteenDatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CanteenDatabaseImplement.Implements
{
public class ManagerStorage : IManagerStorage
{
public ManagerViewModel? GetElement(ManagerSearchModel model)
{
if (string.IsNullOrEmpty(model.Login) && string.IsNullOrEmpty(model.Password) && string.IsNullOrEmpty(model.PhoneNumber) && !model.Id.HasValue)
{
return null;
}
using var context = new CanteenDatabase();
return context.Managers.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.Login) && x.Login == model.Login) ||
(model.Id.HasValue && x.Id == model.Id)
)?.GetViewModel;
}
public List<ManagerViewModel> GetFilteredList(ManagerSearchModel model)
{
if (string.IsNullOrEmpty(model.Login))
{
return new();
}
using var context = new CanteenDatabase();
return context.Managers.Where(x => x.Login.Contains(model.Login)).Select(x => x.GetViewModel).ToList();
}
public List<ManagerViewModel> GetFullList()
{
using var context = new CanteenDatabase();
return context.Managers.Select(x => x.GetViewModel).ToList();
}
public ManagerViewModel? Insert(ManagerBindingModel model)
{
var newManager = Manager.Create(model);
if (newManager == null)
{
return null;
}
using var context = new CanteenDatabase();
context.Managers.Add(newManager);
context.SaveChanges();
return newManager.GetViewModel;
}
public ManagerViewModel? Update(ManagerBindingModel model)
{
using var context = new CanteenDatabase();
var client = context.Managers.FirstOrDefault(x => x.Id == model.Id);
if (client == null)
{
return null;
}
client.Update(model);
context.SaveChanges();
return client.GetViewModel;
}
public ManagerViewModel? Delete(ManagerBindingModel model)
{
using var context = new CanteenDatabase();
var client = context.Managers.FirstOrDefault(x => x.Id == model.Id);
if (client == null)
{
return null;
}
context.Managers.Remove(client);
context.SaveChanges();
return client.GetViewModel;
}
}
}