using ForumContracts.BindingModels; using ForumContracts.SearchModels; using ForumContracts.StoragesContracts; using ForumContracts.ViewModels; using BlogDatabase.Models; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BlogDatabase.Implements { public class TopicStorage : ITopicStorage { public TopicViewModel? Delete(TopicBindingModel model) { using var context = new BlogDatabase(); var element = context.Topics.FirstOrDefault(rec => rec.Id == model.Id); if (element != null) { context.Topics.Remove(element); context.SaveChanges(); return element.GetViewModel; } return null; } public TopicViewModel? GetElement(TopicSearchModel model) { if (string.IsNullOrEmpty(model.Name) && !model.Id.HasValue) { return null; } using var context = new BlogDatabase(); return context.Topics .FirstOrDefault(x => (!string.IsNullOrEmpty(model.Name) && x.Name == model.Name) || (model.Id.HasValue && x.Id == model.Id)) ?.GetViewModel; } public List GetFilteredList(TopicSearchModel model) { using var context = new BlogDatabase(); if (model.CategoryId.HasValue) { return context.Topics .Where(x => x.CategoryId == model.CategoryId) .Select(x => x.GetViewModel) .ToList(); } return context.Topics .Where(x => x.Name.Contains(model.Name)) .Select(x => x.GetViewModel) .ToList(); } public List GetFullList() { using var context = new BlogDatabase(); return context.Topics .Select(x => x.GetViewModel) .ToList(); } public TopicViewModel? Insert(TopicBindingModel model) { var newTopic = Topic.Create(model); if (newTopic == null) { return null; } using var context = new BlogDatabase(); context.Topics.Add(newTopic); context.SaveChanges(); return newTopic.GetViewModel; } public TopicViewModel? Update(TopicBindingModel model) { using var context = new BlogDatabase(); var component = context.Topics.FirstOrDefault(x => x.Id == model.Id); if (component == null) { return null; } component.Update(model); context.SaveChanges(); return component.GetViewModel; } } }