LabSubd/Subd/DataBase/Implements/HumanStorage.cs
2023-05-05 20:47:09 +03:00

103 lines
3.1 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 HumanStorage : IHumanStorage
{
public List<HumanVM> GetFullList()
{
using var context = new LogisticContext();
return context.Humans.FromSqlRaw("Select * From Human").Include(u => u.Status)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public List<HumanVM> GetFilteredList(HumanSM model)
{
if (!model.StatusId.HasValue)
{
return new();
}
using var context = new LogisticContext();
return context.Humans
.FromSqlRaw("Select * FROM Human WHERE status_id = {0}", model.StatusId).Include(u => u.Status)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public HumanVM? GetElement(HumanSM model)
{
if (!model.Id.HasValue && string.IsNullOrEmpty(model.Phone))
{
return null;
}
using var context = new LogisticContext();
return context.Humans
.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id) || (!string.IsNullOrEmpty(model.Phone) && x.Phone.Equals(model.Phone)))
?.GetViewModel;
}
public HumanVM? Insert(HumanBM model)
{
using var context = new LogisticContext();
var newHuman = Human.Create(context, model);
if (newHuman == null)
{
return null;
}
context.Humans.Add(newHuman);
context.SaveChanges();
return newHuman.GetViewModel;
}
public HumanVM? Update(HumanBM model)
{
using var context = new LogisticContext();
using var transaction = context.Database.BeginTransaction();
try
{
var human = context.Humans.FirstOrDefault(rec => rec.Id == model.Id);
if (human == null)
{
return null;
}
human.Update(model);
context.SaveChanges();
transaction.Commit();
return human.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
}
}
public HumanVM? Delete(HumanBM model)
{
using var context = new LogisticContext();
var element = context.Humans
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Humans.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}