Pibd-21_Ievlewa_MD._Precast.../PrecastConcretePlant/PrecastConcretePlantDatabaseImplement/Implements/ComponentStorage.cs

85 lines
3.2 KiB
C#
Raw Normal View History

2024-04-04 21:21:21 +04:00
using PrecastConcretePlantContracts.BindingModels;
using PrecastConcretePlantContracts.SearchModels;
using PrecastConcretePlantContracts.StoragesContracts;
using PrecastConcretePlantContracts.ViewModels;
using PrecastConcretePlantDatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrecastConcretePlantDatabaseImplement.Implements
{
public class ComponentStorage : IComponentStorage
{
public List<ComponentViewModel> GetFullList()
{
2024-05-02 20:47:10 +04:00
using var context = new PrecastConcretePlantDatabase();//подключение к бд, далее - запросы
2024-04-04 21:21:21 +04:00
return context.Components
.Select(x => x.GetViewModel)
.ToList();
}
public List<ComponentViewModel> GetFilteredList(ComponentSearchModel model)
{
if (string.IsNullOrEmpty(model.ComponentName))
{
return new();
}
2024-05-02 20:47:10 +04:00
using var context = new PrecastConcretePlantDatabase();
2024-04-04 21:21:21 +04:00
return context.Components
.Where(x => x.ComponentName.Contains(model.ComponentName))
.Select(x => x.GetViewModel)
.ToList();
}
public ComponentViewModel? GetElement(ComponentSearchModel model)
{
if (string.IsNullOrEmpty(model.ComponentName) && !model.Id.HasValue)
{
return null;
}
2024-05-02 20:47:10 +04:00
using var context = new PrecastConcretePlantDatabase();
2024-04-04 21:21:21 +04:00
return context.Components
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.ComponentName) && x.ComponentName == model.ComponentName)
|| (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public ComponentViewModel? Insert(ComponentBindingModel model)
{
var newComponent = Component.Create(model);
if (newComponent == null)
{
return null;
}
2024-05-02 20:47:10 +04:00
using var context = new PrecastConcretePlantDatabase();
2024-04-04 21:21:21 +04:00
context.Components.Add(newComponent);
context.SaveChanges();
return newComponent.GetViewModel;
}
public ComponentViewModel? Update(ComponentBindingModel model)
{
2024-05-02 20:47:10 +04:00
using var context = new PrecastConcretePlantDatabase();
2024-04-04 21:21:21 +04:00
var component = context.Components.FirstOrDefault(x => x.Id == model.Id);
if (component == null)
{
return null;
}
component.Update(model);
context.SaveChanges();//для сохранения изменений не в копии бд а в самой бд
return component.GetViewModel;
}
public ComponentViewModel? Delete(ComponentBindingModel model)
{
2024-05-02 20:47:10 +04:00
using var context = new PrecastConcretePlantDatabase();
2024-04-04 21:21:21 +04:00
var element = context.Components.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Components.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}