LabSubd/Subd/DataBase/Implements/StatusStorage.cs

90 lines
2.5 KiB
C#

using Contracts.BindingModels;
using Contracts.SearchModel;
using Contracts.Storage;
using Contracts.ViewModels;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataBase.Implements
{
public class StatusStorage : IStatusStorage
{
public List<StatusVM> GetFullList()
{
using var context = new LogisticContext();
return context.Statuses.FromSqlRaw("Select * From Status")
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public StatusVM? GetElement(StatusSM model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new LogisticContext();
return context.Statuses
.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public StatusVM? Insert(StatusBM model)
{
using var context = new LogisticContext();
var newStatus = Status.Create(context, model);
if (newStatus == null)
{
return null;
}
context.Statuses.Add(newStatus);
context.SaveChanges();
return newStatus.GetViewModel;
}
public StatusVM? Update(StatusBM model)
{
using var context = new LogisticContext();
using var transaction = context.Database.BeginTransaction();
try
{
var status = context.Statuses.FirstOrDefault(rec => rec.Id == model.Id);
if (status == null)
{
return null;
}
status.Update(model);
context.SaveChanges();
transaction.Commit();
return status.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
}
}
public StatusVM? Delete(StatusBM model)
{
using var context = new LogisticContext();
var element = context.Statuses
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Statuses.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}