PIbd-21_RazubaevSM_Plumbing.../PlumbingRepair/PlumbingRepairDatabaseImplement/Implements/MessageInfoStorage.cs

82 lines
2.5 KiB
C#

using PlumbingRepairContracts.BindingModels;
using PlumbingRepairContracts.SearchModels;
using PlumbingRepairContracts.StoragesContracts;
using PlumbingRepairContracts.ViewModels;
using PlumbingRepairDatabaseImplement.Models;
namespace PlumbingRepairDatabaseImplement.Implements
{
public class MessageInfoStorage : IMessageInfoStorage
{
public List<MessageInfoViewModel> GetFullList()
{
using var context = new PlumbingRepairDatabase();
return context.Messages
.Select(x => x.GetViewModel)
.ToList();
}
public List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model)
{
using var context = new PlumbingRepairDatabase();
if (model.ClientId.HasValue && model.Page.HasValue && model.PageSize.HasValue)
{
return context.Messages
.Where(x => x.ClientId == model.ClientId)
.Skip(model.PageSize.Value * model.Page.Value)
.Take(model.PageSize.Value)
.Select(x => x.GetViewModel)
.ToList();
}
else if (model.Page.HasValue && model.PageSize.HasValue)
{
return context.Messages
.Skip(model.PageSize.Value * model.Page.Value)
.Take(model.PageSize.Value)
.Select(x => x.GetViewModel)
.ToList();
}
return new();
}
public MessageInfoViewModel? GetElement(MessageInfoSearchModel model)
{
if (string.IsNullOrEmpty(model.MessageId))
return null;
using var context = new PlumbingRepairDatabase();
return context.Messages
.FirstOrDefault(x => x.MessageId == model.MessageId)?.GetViewModel;
}
public MessageInfoViewModel? Insert(MessageInfoBindingModel model)
{
using var context = new PlumbingRepairDatabase();
model.ClientId = context.Clients.FirstOrDefault(x => x.Email.Equals(model.SenderName))?.Id;
var newMessageInfo = MessageInfo.Create(model);
if (newMessageInfo == null || context.Messages.Any(x => x.MessageId.Equals(model.MessageId)))
{
return null;
}
context.Messages.Add(newMessageInfo);
context.SaveChanges();
return newMessageInfo.GetViewModel;
}
public MessageInfoViewModel? Update(MessageInfoBindingModel model)
{
using var context = new PlumbingRepairDatabase();
var message = context.Messages.FirstOrDefault(x => x.MessageId == model.MessageId);
if (message == null)
{
return null;
}
message.Update(model);
context.SaveChanges();
return message.GetViewModel;
}
}
}