Coursach/Course/DatabaseImplement/Implements/ProductionStorage.cs

78 lines
2.4 KiB
C#
Raw Normal View History

2024-04-27 21:07:45 +04:00
using Contracts.BindingModels;
using Contracts.SearchModels;
using Contracts.StoragesContracts;
using Contracts.ViewModels;
using DatabaseImplement.Models;
namespace DatabaseImplement.Implements
{
public class ProductionionStorage : IProductionStorage
{
public ProductionViewModel? Delete(ProductionBindingModel model)
{
using var context = new FactoryGoWorkDatabase();
var newProduction = context.Productions.FirstOrDefault(x => x.Id == model.Id);
if (newProduction == null)
return null;
context.Productions.Remove(newProduction);
context.SaveChanges();
return newProduction.GetViewModel;
}
public ProductionViewModel? GetElement(ProductionSearchModel model)
{
using var context = new FactoryGoWorkDatabase();
return context.Productions.FirstOrDefault(x => (!string.IsNullOrEmpty(model.Name) && x.Name.Contains(model.Name)) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public List<ProductionViewModel> GetFilteredList(ProductionSearchModel model)
{
if (!model.Id.HasValue && string.IsNullOrEmpty(model.Name) && !model.UserId.HasValue)
{
return new();
}
using var context = new FactoryGoWorkDatabase();
if (model.Id.HasValue)
{
return context.Productions.Where(x => x.Id == model.Id).Select(x => x.GetViewModel).ToList();
}
else if (model.UserId.HasValue)
{
return context.Productions.Where(x => x.UserId == model.Id).Select(x => x.GetViewModel).ToList();
}
else
{
return context.Productions.Where(x => model.Name == x.Name).Select(x => x.GetViewModel).ToList();
}
}
public List<ProductionViewModel> GetFullList()
{
using var context = new FactoryGoWorkDatabase();
return context.Productions.Select(x => x.GetViewModel).ToList();
}
public ProductionViewModel? Insert(ProductionBindingModel model)
{
using var context = new FactoryGoWorkDatabase();
var newProduction = Production.Create(context, model);
if (newProduction == null)
return null;
context.Productions.Add(newProduction);
context.SaveChanges();
return newProduction.GetViewModel;
}
public ProductionViewModel? Update(ProductionBindingModel model)
{
using var context = new FactoryGoWorkDatabase();
var newProduction = context.Productions.FirstOrDefault(x => x.Id == model.Id);
if (newProduction == null)
return null;
newProduction.Update(model);
context.SaveChanges();
return newProduction.GetViewModel;
}
}
}