SUBD_PIbd-21_Balberova_D.N./BeautySaloon/BeautySaloonDatabaseImplement/Implements/ServiceStorage.cs

111 lines
3.6 KiB
C#
Raw Permalink Normal View History

2023-03-28 21:24:52 +04:00
using BeautySaloonContracts.BindingModels;
using BeautySaloonContracts.SearchModels;
using BeautySaloonContracts.StoragesContracts;
using BeautySaloonContracts.ViewModels;
2023-03-30 13:59:00 +04:00
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using System.Diagnostics;
2023-03-28 21:24:52 +04:00
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)
{
2023-03-29 20:00:53 +04:00
using var context = new NewdbContext();
model.Id = context.Services
.Count() > 0 ? context.Services.Max(x => x.Id) + 1 : 1;
2023-03-28 21:24:52 +04:00
var newService = Service.Create(model);
if (newService == null)
{
return null;
}
context.Services.Add(newService);
context.SaveChanges();
return newService.GetViewModel;
}
2023-03-30 13:59:00 +04:00
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();
}
2023-03-28 21:24:52 +04:00
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;
}
}
}