2023-11-30 23:20:29 +04:00

94 lines
2.1 KiB
C#

using Contracts.BindingModels;
using Contracts.SearchModels;
using Contracts.StoragesContracts;
using Contracts.ViewModels;
using DatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DatabaseImplement.Implements
{
public class ShapeStorage : IShapeStorage
{
public ShapeViewModel? Delete(ShapeBindingModel model)
{
using var context = new COPcontext();
var element = context.Shapes.FirstOrDefault(rec => rec.Id ==
model.Id);
if (element != null)
{
context.Shapes.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
public ShapeViewModel? GetElement(ShapeSearchModel model)
{
if (string.IsNullOrEmpty(model.Name) && !model.Id.HasValue)
{
return null;
}
using var context = new COPcontext();
return context.Shapes
.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.Name) && x.Name ==
model.Name) ||
(model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public List<ShapeViewModel> GetFilteredList(ShapeSearchModel model)
{
if (string.IsNullOrEmpty(model.Name))
{
return new();
}
using var context = new COPcontext();
return context.Shapes
.Where(x => x.Name.Contains(model.Name))
.Select(x => x.GetViewModel)
.ToList();
}
public List<ShapeViewModel> GetFullList()
{
using var context = new COPcontext();
return context.Shapes
.Select(x => x.GetViewModel)
.ToList();
}
public ShapeViewModel? Insert(ShapeBindingModel model)
{
var newComponent = Shape.Create(model);
if (newComponent == null)
{
return null;
}
using var context = new COPcontext();
context.Shapes.Add(newComponent);
context.SaveChanges();
return newComponent.GetViewModel;
}
public ShapeViewModel? Update(ShapeBindingModel model)
{
using var context = new COPcontext();
var component = context.Shapes.FirstOrDefault(x => x.Id ==
model.Id);
if (component == null)
{
return null;
}
component.Update(model);
context.SaveChanges();
return component.GetViewModel;
}
}
}