PIbd-23_Starostin_I.K._Cour.../STODataBaseImplement/CarPartStorage.cs

84 lines
2.6 KiB
C#

using STOContracts.BindingModels;
using STOContracts.SearchModels;
using STOContracts.StorageContracts;
using STOContracts.ViewModels;
using STODatabaseImplement;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DatabaseImplement
{
public class CarPartStorage : ICarPartStorage
{
public List<CarPartViewModel> GetFullList()
{
using var context = new STODatabase();
return context.CarParts.Select(x => x.GetViewModel).ToList();
}
public List<CarPartViewModel> GetFilteredList(CarPartSearchModel model)
{
if (!model.Id.HasValue)
{
return new();
}
using var context = new STODatabase();
return context.CarParts.Where(x => x.Id == model.Id).Select(x => x.GetViewModel).ToList();
}
public CarPartViewModel? GetElement(CarPartSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new STODatabase();
return context.CarParts.FirstOrDefault(x =>
(x.Id == model.Id))
?.GetViewModel;
}
public CarPartViewModel? Insert(CarPartBindingModel model)
{
var newCarPart = CarPart.Create(model);
if (newCarPart == null)
{
return null;
}
using var context = new STODatabase();
context.CarParts.Add(newCarPart);
context.SaveChanges();
return newCarPart.GetViewModel;
}
public CarPartViewModel? Update(CarPartBindingModel model)
{
using var context = new STODatabase();
var component = context.CarParts.FirstOrDefault(x => x.Id == model.Id);
if (component == null)
{
return null;
}
component.Update(model);
context.SaveChanges();
return component.GetViewModel;
}
public CarPartViewModel? Delete(CarPartBindingModel model)
{
using var context = new STODatabase();
var element = context.CarParts.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.CarParts.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}