109 lines
3.5 KiB
C#

using DeviceContracts.BindingModels;
using DeviceContracts.SearchModels;
using DeviceContracts.StoragesContracts;
using DeviceContracts.ViewModels;
using DeviceDatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DeviceDatabaseImplement.Implements
{
public class ServiceStorage : IServiceStorage
{
public List<ServiceViewModel> GetFullList()
{
using var context = new DeviceDatabase();
return context.Services.Select(x => x.GetViewModel).ToList();
}
public List<ServiceViewModel> GetFilteredList(ServiceSearchModel model)
{
if (string.IsNullOrEmpty(model.Description) &&
model.DeviceId == 0 &&
model.StartDate == null &&
model.EndDate == null)
{
return new();
}
using var context = new DeviceDatabase();
return context.Services
.Where(x => (string.IsNullOrEmpty(model.Description) ||
x.Description == model.Description) && (model.DeviceId == 0 ||
x.DeviceId == model.DeviceId) && (model.StartDate == null ||
x.StartDate >= model.StartDate) && (model.EndDate == null ||
x.EndDate <= model.EndDate))
.Select(x => x.GetViewModel).ToList();
}
public ServiceViewModel? GetElement(ServiceSearchModel model)
{
if (string.IsNullOrEmpty(model.Description) &&
model.DeviceId == 0 &&
model.StartDate == null &&
model.EndDate == null)
{
return null;
}
using var context = new DeviceDatabase();
return context.Services
.FirstOrDefault(x => (string.IsNullOrEmpty(model.Description) ||
x.Description == model.Description) && (model.DeviceId == 0 ||
x.DeviceId == model.DeviceId) && (model.StartDate == null ||
x.StartDate >= model.StartDate) && (model.EndDate == null ||
x.EndDate <= model.EndDate))
?.GetViewModel;
}
public ServiceViewModel? Insert(ServiceBindingModel model)
{
var newService = Service.Create(model);
if (newService == null)
{
return null;
}
using var context = new DeviceDatabase();
context.Services.Add(newService);
context.SaveChanges();
return newService.GetViewModel;
}
public ServiceViewModel? Update(ServiceBindingModel model)
{
using var context = new DeviceDatabase();
var service = context.Services
.FirstOrDefault(x => x.Id == model.Id);
if (service == null)
{
return null;
}
service.Update(model);
context.SaveChanges();
return service.GetViewModel;
}
public ServiceViewModel? Delete(ServiceBindingModel model)
{
using var context = new DeviceDatabase();
var service = context.Services
.FirstOrDefault(x => x.Id == model.Id);
if (service != null)
{
context.Services.Remove(service);
context.SaveChanges();
return service.GetViewModel;
}
return null;
}
}
}