SUBD_Aleikin/Restaurant/RestaurantDatabaseImplement/Implements/ProviderStorage.cs

98 lines
3.1 KiB
C#

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 ProviderStorage : IProviderStorage
{
public List<ProviderViewModel> GetFullList()
{
using var context = new RestaurantDatabase();
return context.Providers.Select(x => x.GetViewModel).ToList();
}
public List<ProviderViewModel> GetFilteredList(ProviderSearchModel model)
{
using var context = new RestaurantDatabase();
if (model.Id.HasValue)
{
return context.Providers
.Where(x => x.Id == model.Id)
.Select(x => x.GetViewModel)
.ToList();
}
else if (model.Name != null)
{
return context.Providers
.Where(x => x.Name == model.Name)
.Select(x => x.GetViewModel)
.ToList();
}
else
{
return new();
}
}
public ProviderViewModel? GetElement(ProviderSearchModel model)
{
if (string.IsNullOrEmpty(model.Name) && !model.Id.HasValue)
{
return null;
}
using var context = new RestaurantDatabase();
return context.Providers
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.Name) && x.Name == model.Name)
|| (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public ProviderViewModel? Insert(ProviderBindingModel model)
{
var newProvider = Provider.Create(model);
if (newProvider == null)
{
return null;
}
using var context = new RestaurantDatabase();
context.Providers.Add(newProvider);
context.SaveChanges();
return newProvider.GetViewModel;
}
public ProviderViewModel? Update(ProviderBindingModel model)
{
using var context = new RestaurantDatabase();
var Provider = context.Providers.FirstOrDefault(x => x.Id == model.Id);
if (Provider == null)
{
return null;
}
Provider.Update(model);
context.SaveChanges();
return Provider.GetViewModel;
}
public ProviderViewModel? Delete(ProviderBindingModel model)
{
using var context = new RestaurantDatabase();
var element = context.Providers.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Providers.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}