Zhelovanov_Dmitrii_COP/DatabaseImplement/Implements/BookStorage.cs
2023-11-30 23:20:29 +04:00

95 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.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DatabaseImplement.Implements
{
public class BookStorage : IBookStorage
{
public BookViewModel? Delete(BookBindingModel model)
{
using var context = new COPcontext();
var element = context.Books.FirstOrDefault(rec => rec.Id ==
model.Id);
if (element != null)
{
context.Books.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
public BookViewModel? GetElement(BookSearchModel model)
{
if (string.IsNullOrEmpty(model.Name) && !model.Id.HasValue)
{
return null;
}
using var context = new COPcontext();
return context.Books
.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.Name) && x.Name ==
model.Name) ||
(model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public List<BookViewModel> GetFilteredList(BookSearchModel model)
{
if (string.IsNullOrEmpty(model.Name))
{
return new();
}
using var context = new COPcontext();
return context.Books
.Where(x => x.Name.Contains(model.Name))
.Select(x => x.GetViewModel)
.ToList();
}
public List<BookViewModel> GetFullList()
{
using var context = new COPcontext();
return context.Books
.Select(x => x.GetViewModel)
.ToList();
}
public BookViewModel? Insert(BookBindingModel model)
{
var newComponent = Book.Create(model);
if (newComponent == null)
{
return null;
}
using var context = new COPcontext();
context.Books.Add(newComponent);
context.SaveChanges();
return newComponent.GetViewModel;
}
public BookViewModel? Update(BookBindingModel model)
{
using var context = new COPcontext();
var component = context.Books.FirstOrDefault(x => x.Id ==
model.Id);
if (component == null)
{
return null;
}
component.Update(model);
context.SaveChanges();
return component.GetViewModel;
}
}
}