COP_labs/OnlineStoreDatabase/Storages/StatusStorage.cs

116 lines
3.5 KiB
C#

using OnlineShopContracts.BindingModels;
using OnlineShopContracts.ViewModels;
using OnlineShopDatabase.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OnlineShopDatabase.Storages
{
public class StatusStorage
{
public List<StatusViewModel> GetFullList()
{
using var context = new OnlineShopDatabase();
return context.Statuses.Select(x => x.GetViewModel).ToList();
}
public List<StatusViewModel> GetFilteredList(StatusBindingModel model)
{
using var context = new OnlineShopDatabase();
//поиск по названию статуса
if (!string.IsNullOrEmpty(model.Name))
{
return context.Statuses
.Where(x => x.Name == model.Name)
.Select(x => x.GetViewModel)
.ToList();
}
return new();
}
//получение по id статуса
public StatusViewModel? GetElement(StatusBindingModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new OnlineShopDatabase();
return context.Statuses.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
}
public bool Insert(StatusBindingModel model)
{
var newStatus = Status.Create(model);
if (newStatus == null)
{
return false;
}
using var context = new OnlineShopDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
context.Statuses.Add(newStatus);
context.SaveChanges();
transaction.Commit();
return true;
}
catch (Exception ex)
{
transaction.Rollback();
return false;
throw;
}
}
public bool Update(StatusBindingModel model)
{
using var context = new OnlineShopDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
var status = context.Statuses.FirstOrDefault(x => x.Id == model.Id);
if (status == null)
{
throw new Exception("Статус не найден");
}
status.Update(model);
context.SaveChanges();
transaction.Commit();
return true;
}
catch
{
transaction.Rollback();
return false;
}
}
public bool Delete(StatusBindingModel model)
{
using var context = new OnlineShopDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
var status = context.Statuses.FirstOrDefault(rec => rec.Id == model.Id);
if (status == null)
{
throw new Exception("Статус не найден");
}
context.Statuses.Remove(status);
context.SaveChanges();
transaction.Commit();
return true;
}
catch
{
transaction.Rollback();
return false;
}
}
}
}