SUBD_PIbd-21_Balberova_D.N./BeautySaloon/BeautySaloonDatabaseImplement/Implements/ServiceStorage.cs
2023-03-30 13:59:00 +04:00

111 lines
3.6 KiB
C#

using BeautySaloonContracts.BindingModels;
using BeautySaloonContracts.SearchModels;
using BeautySaloonContracts.StoragesContracts;
using BeautySaloonContracts.ViewModels;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using System.Diagnostics;
namespace BeautySaloonDatabaseImplement.Implements
{
public class ServiceStorage : IServiceStorage
{
public ServiceViewModel? Delete(ServiceBindingModel model)
{
using var context = new NewdbContext();
var element = context.Services
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Services.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
public ServiceViewModel? GetElement(ServiceSearchModel model)
{
using var context = new NewdbContext();
if (model.Id.HasValue)
return context.Services
.FirstOrDefault(x => x.Id == model.Id)?
.GetViewModel;
if (!string.IsNullOrEmpty(model.Name))
return context.Services
.FirstOrDefault(x => x.Name.Equals(model.Name))?
.GetViewModel;
return null;
}
public List<ServiceViewModel> GetFilteredList(ServiceSearchModel model)
{
if (string.IsNullOrEmpty(model.Name))
{
return new();
}
using var context = new NewdbContext();
return context.Services
.Where(x => x.Name.Contains(model.Name))
.Select(x => x.GetViewModel)
.ToList();
}
public List<ServiceViewModel> GetFullList()
{
using var context = new NewdbContext();
return context.Services
.Select(x => x.GetViewModel)
.ToList();
}
public ServiceViewModel? Insert(ServiceBindingModel model)
{
using var context = new NewdbContext();
model.Id = context.Services
.Count() > 0 ? context.Services.Max(x => x.Id) + 1 : 1;
var newService = Service.Create(model);
if (newService == null)
{
return null;
}
context.Services.Add(newService);
context.SaveChanges();
return newService.GetViewModel;
}
public List<ReportViewModel> ReadMostPopular()
{
using var context = new NewdbContext();
/*var temp = context.Services
.Select(x => x.GetViewModel)
.ToList();*/
return context.ServiceOrders
.Include(x => x.Service)
.GroupBy(x => x.Service.Name)
.Select(x => new ReportViewModel()
{
Name = x.Key,
Sum = x.Sum(x => x.Service.Price)
})
.OrderByDescending(x => x.Sum)
.ToList();
}
public ServiceViewModel? Update(ServiceBindingModel model)
{
using var context = new NewdbContext();
var service = context.Services
.FirstOrDefault(x => x.Id == model.Id);
if (service == null)
{
return null;
}
service.Update(model);
context.SaveChanges();
return service.GetViewModel;
}
}
}