PIbd-21_BatylkinaAO_MusoevD.../Canteen/CanteenDatabaseImplement/Implements/TablewareStorage.cs
2023-05-19 03:39:58 +04:00

96 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 TablewareStorage : ITablewareStorage
{
public TablewareViewModel? GetElement(TablewareSearchModel model)
{
if (!model.Id.HasValue && string.IsNullOrEmpty(model.TablewareName))
{
return null;
}
using var context = new CanteenDatabase();
return context.Tablewares.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id) || (!string.IsNullOrEmpty(model.TablewareName) && x.TablewareName == model.TablewareName))?.GetViewModel;
}
public List<TablewareViewModel> GetFilteredList(TablewareSearchModel model)
{
if (!model.VisitorId.HasValue)
{
return new();
}
using var context = new CanteenDatabase();
return context.Tablewares
.Where(x => (model.Id.HasValue && x.Id == model.Id) || (model.VisitorId.HasValue && model.VisitorId == x.VisitorId))
.Select(x => x.GetViewModel).ToList();
}
public List<TablewareViewModel> GetFullList()
{
using var context = new CanteenDatabase();
return context.Tablewares.Select(x => x.GetViewModel).ToList();
}
public TablewareViewModel? Insert(TablewareBindingModel model)
{
var newTableware = Tableware.Create(model);
if (newTableware == null)
{
return null;
}
using var context = new CanteenDatabase();
context.Tablewares.Add(newTableware);
context.SaveChanges();
return newTableware.GetViewModel;
}
public TablewareViewModel? Update(TablewareBindingModel model)
{
using var context = new CanteenDatabase();
var cook = context.Tablewares.FirstOrDefault(x => x.Id == model.Id);
if (cook == null)
{
return null;
}
cook.Update(model);
context.SaveChanges();
return cook.GetViewModel;
}
public TablewareViewModel? Delete(TablewareBindingModel model)
{
using var context = new CanteenDatabase();
var cook = context.Tablewares.FirstOrDefault(x => x.Id == model.Id);
if (cook != null)
{
context.Tablewares.Remove(cook);
context.SaveChanges();
return cook.GetViewModel;
}
return null;
}
}
}