using BankContracts.BindingModels; using BankContracts.SearchModels; using BankContracts.StoragesContracts; using BankContracts.ViewModels; using BankDatabaseImplement.Models; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BankDatabaseImplement.Implements { public class OperatorStorage : IOperatorStorage { public List GetFullList() { using var context = new BankDatabase(); return context.Operators .Select(x => x.GetViewModel) .ToList(); } public List GetFilteredList(OperatorSearchModel model) { if (!model.Id.HasValue && string.IsNullOrEmpty(model.Login) && string.IsNullOrEmpty(model.Password)) { return new(); } using var context = new BankDatabase(); if (!string.IsNullOrEmpty(model.Login) && !string.IsNullOrEmpty(model.Password)) { return context.Operators .Where(x => x.Login == model.Login || x.Password == model.Password) .Select(x => x.GetViewModel) .ToList(); } else { return context.Operators .Where(x => x.Id == model.Id) .Select(x => x.GetViewModel) .ToList(); } } public OperatorViewModel? GetElement(OperatorSearchModel model) { if (!model.Id.HasValue) { return null; } using var context = new BankDatabase(); return context.Operators .FirstOrDefault(x => x.Id == model.Id) ?.GetViewModel; } public OperatorViewModel? Insert(OperatorBindingModel model) { using var context = new BankDatabase(); var newOperator = Operator.Create(model); if (newOperator == null) { return null; } context.Operators.Add(newOperator); context.SaveChanges(); return newOperator.GetViewModel; } public OperatorViewModel? Update(OperatorBindingModel model) { using var context = new BankDatabase(); var operatorUpd = context.Operators.FirstOrDefault(x => x.Id == model.Id); if (operatorUpd == null) { return null; } operatorUpd.Update(model); context.SaveChanges(); return operatorUpd.GetViewModel; } public OperatorViewModel? Delete(OperatorBindingModel model) { using var context = new BankDatabase(); var element = context.Operators.FirstOrDefault(rec => rec.Id == model.Id); if (element != null) { context.Operators.Remove(element); context.SaveChanges(); return element.GetViewModel; } return null; } } }