using SecuritySystemContracts.BindingModels; using SecuritySystemContracts.SearchModels; using SecuritySystemContracts.StoragesContracts; using SecuritySystemContracts.ViewModels; using SecuritySystemDatabaseImplement.Models; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SecuritySystemDatabaseImplement.Implements { public class SecureStorage : ISecureStorage { public List GetFullList() { using var context = new SecuritySystemDatabase(); return context.Secures .Include(x => x.Sensors) .ThenInclude(x => x.Sensor) .ToList() .Select(x => x.GetViewModel) .ToList(); } public List GetFilteredList(SecureSearchModel model) { if (string.IsNullOrEmpty(model.SecureName)) { return new(); } using var context = new SecuritySystemDatabase(); return context.Secures .Include(x => x.Sensors) .ThenInclude(x => x.Sensor) .Where(x => x.SecureName.Contains(model.SecureName)) .ToList() .Select(x => x.GetViewModel) .ToList(); } public SecureViewModel? GetElement(SecureSearchModel model) { if (string.IsNullOrEmpty(model.SecureName) && !model.Id.HasValue) { return null; } using var context = new SecuritySystemDatabase(); return context.Secures .Include(x => x.Sensors) .ThenInclude(x => x.Sensor) .FirstOrDefault(x => (!string.IsNullOrEmpty(model.SecureName) && x.SecureName == model.SecureName) || (model.Id.HasValue && x.Id == model.Id)) ?.GetViewModel; } public SecureViewModel? Insert(SecureBindingModel model) { using var context = new SecuritySystemDatabase(); var newSecure = Secure.Create(context, model); if (newSecure == null) { return null; } context.Secures.Add(newSecure); context.SaveChanges(); return newSecure.GetViewModel; } public SecureViewModel? Update(SecureBindingModel model) { using var context = new SecuritySystemDatabase(); using var transaction = context.Database.BeginTransaction(); try { var secure = context.Secures.FirstOrDefault(rec => rec.Id == model.Id); if (secure == null) { return null; } secure.Update(model); context.SaveChanges(); secure.UpdateSensors(context, model); transaction.Commit(); return secure.GetViewModel; } catch { transaction.Rollback(); throw; } } public SecureViewModel? Delete(SecureBindingModel model) { using var context = new SecuritySystemDatabase(); var element = context.Secures .Include(x => x.Sensors) .Include(x => x.Orders) .FirstOrDefault(rec => rec.Id == model.Id); if (element != null) { context.Secures.Remove(element); context.SaveChanges(); return element.GetViewModel; } return null; } } }