using PortalAccountsContracts.BindingModels; using PortalAccountsContracts.SearchModels; using PortalAccountsContracts.StoragesContracts; using PortalAccountsContracts.ViewModels; using PortalAccountsDatabaseImplement.Models; using Microsoft.EntityFrameworkCore; namespace PortalAccountsDatabaseImplement.Implements { public class AccountStorage : IAccountStorage { public List GetFullList() { using var context = new PortalAccountsDatabase(); return context.Accounts .Include(x => x.Role) .Select(x => x.GetViewModel) .ToList(); } public List GetFilteredList(AccountSearchModel model) { using var context = new PortalAccountsDatabase(); if (model.RoleId.HasValue) { return context.Accounts .Include(x => x.Role) .Where(x => x.RoleId == model.RoleId) .Select(x => x.GetViewModel) .ToList(); } return new(); } public AccountViewModel? GetElement(AccountSearchModel model) { if (string.IsNullOrEmpty(model.Login) && !model.Id.HasValue) { return null; } using var context = new PortalAccountsDatabase(); return context.Accounts .Include(x => x.Role) .FirstOrDefault(x => !string.IsNullOrEmpty(model.Login) && x.Login == model.Login || model.Id.HasValue && x.Id == model.Id) ?.GetViewModel; } public AccountViewModel? Insert(AccountBindingModel model) { var newAccount = Account.Create(model); if (newAccount == null) { return null; } using var context = new PortalAccountsDatabase(); context.Accounts.Add(newAccount); context.SaveChanges(); return context.Accounts .Include(x => x.Role) .FirstOrDefault(x => x.Id == newAccount.Id) ?.GetViewModel; } public AccountViewModel? Update(AccountBindingModel model) { using var context = new PortalAccountsDatabase(); var account = context.Accounts.FirstOrDefault(x => x.Id == model.Id); if (account == null) { return null; } account.Update(model); context.SaveChanges(); return context.Accounts .Include(x => x.Role) .FirstOrDefault(x => x.Id == model.Id) ?.GetViewModel; } public AccountViewModel? Delete(AccountBindingModel model) { using var context = new PortalAccountsDatabase(); var element = context.Accounts.FirstOrDefault(rec => rec.Id == model.Id); if (element != null) { var deletedElement = context.Accounts .Include(x => x.Role) .FirstOrDefault(x => x.Id == model.Id) ?.GetViewModel; context.Accounts.Remove(element); context.SaveChanges(); return deletedElement; } return null; } } }