using ConfectioneryContracts.BindingModels; using ConfectioneryContracts.SearchModels; using ConfectioneryContracts.StoragesContract; using ConfectioneryContracts.ViewModels; using ConfectioneryDatabaseImplement.Models; using Microsoft.EntityFrameworkCore; namespace ConfectioneryDatabaseImplement { public class MessageInfoStorage : IMessageInfoStorage { public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) { using var context = new ConfectioneryDatabase(); if (model.MessageId != null) { return context.Messages .Include(x => x.ReplyMessage) .FirstOrDefault(x => x.MessageId == model.MessageId)?.GetViewModel; } return null; } public List GetFilteredList(MessageInfoSearchModel model) { using var context = new ConfectioneryDatabase(); var res = context.Messages .Include(x => x.ReplyMessage) .Where(x => !model.ClientId.HasValue || x.ClientId == model.ClientId) .Select(x => x.GetViewModel); if (!(model.Page.HasValue && model.PageSize.HasValue)) { return res.ToList(); } return res.Skip((model.Page.Value - 1) * model.PageSize.Value).Take(model.PageSize.Value).ToList(); } public List GetFullList() { using var context = new ConfectioneryDatabase(); return context.Messages .Include(x => x.ReplyMessage) .Select(x => x.GetViewModel) .ToList(); } public MessageInfoViewModel? Insert(MessageInfoBindingModel model) { using var context = new ConfectioneryDatabase(); var newMessage = MessageInfo.Create(model); if (newMessage == null || context.Messages.Any(x => x.MessageId.Equals(model.MessageId))) { return null; } context.Messages.Add(newMessage); context.SaveChanges(); return newMessage.GetViewModel; } public MessageInfoViewModel? Update(MessageInfoBindingModel model) { using var context = new ConfectioneryDatabase(); var res = context.Messages.FirstOrDefault(x => x.MessageId.Equals(model.MessageId)); if (res != null) { res.Update(model); context.SaveChanges(); } return res?.GetViewModel; } } }