SUBD_Aleikin/Restaurant/RestaurantDatabaseImplement/Implements/ComponentStorage.cs

114 lines
3.8 KiB
C#
Raw Normal View History

using Microsoft.EntityFrameworkCore;
using RestaurantContracts.BindingModels;
using RestaurantContracts.SearchModels;
using RestaurantContracts.StoragesContracts;
using RestaurantContracts.ViewModels;
using RestaurantDatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RestaurantDatabaseImplement.Implements
{
public class ComponentStorage : IComponentStorage
{
public List<ComponentViewModel> GetFullList()
{
using var context = new RestaurantDatabase();
return context.Components
.Include(x => x.Providers)
.ThenInclude(x => x.Provider)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public List<ComponentViewModel> GetFilteredList(ComponentSearchModel model)
{
using var context = new RestaurantDatabase();
if (model.Id.HasValue)
{
return context.Components
.Include(x => x.Providers)
.ThenInclude(x => x.ProviderId)
.Where(x => x.Id == model.Id)
.Select(x => x.GetViewModel)
.ToList();
}
else if (model.Name != null)
{
return context.Components
.Include(x => x.Providers)
.ThenInclude(x => x.ProviderId)
.Where(x => x.Name == model.Name)
.Select(x => x.GetViewModel)
.ToList();
}
else
{
return new();
}
}
public ComponentViewModel? GetElement(ComponentSearchModel model)
{
if (string.IsNullOrEmpty(model.Name) &&
!model.Id.HasValue)
{
return null;
}
using var context = new RestaurantDatabase();
return context.Components
.Include(x => x.Providers)
.ThenInclude(x => x.Provider)
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.Name) &&
x.Name == model.Name) ||
(model.Id.HasValue && x.Id ==
model.Id))
?.GetViewModel;
}
public ComponentViewModel? Insert(ComponentBindingModel model)
{
using var context = new RestaurantDatabase();
var newComponent = Component.Create(context, model);
if (newComponent == null)
{
return null;
}
context.Components.Add(newComponent);
context.SaveChanges();
return newComponent.GetViewModel;
}
public ComponentViewModel? Update(ComponentBindingModel model)
{
using var context = new RestaurantDatabase();
var element = context.Components
.Include(x => x.Providers)
.ThenInclude(x => x.ProviderId)
.FirstOrDefault(x => x.Id == model.Id);
if (element == null)
{
return null;
}
element.Update(model);
context.SaveChanges();
return GetElement(new ComponentSearchModel { Id = element.Id });
}
public ComponentViewModel? Delete(ComponentBindingModel model)
{
using var context = new RestaurantDatabase();
var element = context.Components
.Include(x => x.Providers)
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Components.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}