SUBD_Gerimovich_Ilya_PIbd-22/FurnitureAssembly/FurnitureAssemblyDatabaseImplement/Implements/UsersStorage.cs
platoff aeeee 4b0700dee1 20
2024-05-24 14:23:37 +04:00

128 lines
3.7 KiB
C#

using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.SearchModels;
using FurnitureAssemblyContracts.StoragesContracts;
using FurnitureAssemblyContracts.ViewModels;
using FurnitureAssemblyDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace FurnitureAssemblyDatabaseImplement.Implements
{
public class UsersStorage : IUsersStorage
{
public List<UsersViewModel> GetFullList()
{
using var context = new FurnitureAssemblyDatabase();
return context.Userss
.Include(x => x.Komments)
.ThenInclude(x => x.Komment)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public List<UsersViewModel> GetFilteredList(UsersSearchModel model)
{
if (string.IsNullOrEmpty(model.UsersName))
{
return new();
}
using var context = new FurnitureAssemblyDatabase();
return context.Userss
.Include(x => x.Komments)
.ThenInclude(x => x.Komment)
.Where(x => x.UsersName.Contains(model.UsersName))
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public UsersViewModel? GetElement(UsersSearchModel model)
{
if (string.IsNullOrEmpty(model.UsersName) && !model.Id.HasValue)
{
return null;
}
using var context = new FurnitureAssemblyDatabase();
return context.Userss
.Include(x => x.Komments)
.ThenInclude(x => x.Komment)
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.UsersName) && x.UsersName == model.UsersName) ||
model.Id.HasValue && x.Id == model.Id)?.GetViewModel;
}
public UsersViewModel? Insert(UsersBindingModel model)
{
using var context = new FurnitureAssemblyDatabase();
var newUser = Users.Create(context, model);
if (newUser == null)
{
return null;
}
context.Userss.Add(newUser);
context.SaveChanges();
return newUser.GetViewModel;
}
public UsersViewModel? Update(UsersBindingModel model)
{
using var context = new FurnitureAssemblyDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
var user = context.Userss.FirstOrDefault(rec => rec.Id == model.Id);
if (user == null)
{
return null;
}
user.Update(model);
context.SaveChanges();
user.UpdateWorkPieces(context, model);
transaction.Commit();
return user.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
}
}
public UsersViewModel? Delete(UsersBindingModel model)
{
using var context = new FurnitureAssemblyDatabase();
var element = context.Userss
.Include(x => x.Komments)
.Include(x => x.Ads)
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Userss.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}