using ForumContracts.BindingModels; using ForumContracts.SearchModels; using ForumContracts.StorageContracts; using ForumContracts.ViewModels; using ForumDatabaseImplement.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ForumDatabaseImplement.Implements { public class CategoryStorage : ICategoryStorage { public CategoryViewModel? Delete(CategoryBindingModel model) { using var context = new ForumDataBase(); var res = context.Categories .FirstOrDefault(x => x.Id == model.Id); if (res != null) { context.Categories.Remove(res); context.SaveChanges(); } return res?.GetViewModel; } public CategoryViewModel? GetElement(CategorySearchModel model) { using var context = new ForumDataBase(); if (model.Id.HasValue) return context.Categories .FirstOrDefault(x => x.Id == model.Id) ?.GetViewModel; return null; } public List GetFilteredList(CategorySearchModel model) { if (model == null) { return new(); } if (model.Id.HasValue) { var res = GetElement(model); return res != null ? new() { res } : new(); } if (model.Name != null) { using var context = new ForumDataBase(); return context.Categories .Where(x => x.Name.Equals(model.Name)) .Select(x => x.GetViewModel) .ToList(); } return new(); } public List GetFullList() { using var context = new ForumDataBase(); return context.Categories .Select(x => x.GetViewModel) .ToList(); } public CategoryViewModel? Insert(CategoryBindingModel model) { using var context = new ForumDataBase(); var res = Category.Create(model); if (res != null) { context.Categories.Add(res); context.SaveChanges(); } return res?.GetViewModel; } public CategoryViewModel? Update(CategoryBindingModel model) { using var context = new ForumDataBase(); var res = context.Categories .FirstOrDefault(x => x.Id == model.Id); if (res != null) { res.Update(model); context.SaveChanges(); } return res?.GetViewModel; } } }