ComputerHardwareStore_YouAr.../ComputerHardwareStore/ComputerHardwareStoreDatabaseImplement/Implements/CommentStorage.cs

78 lines
2.6 KiB
C#

using ComputerHardwareStoreContracts.BindingModels;
using ComputerHardwareStoreContracts.SearchModels;
using ComputerHardwareStoreContracts.StorageContracts;
using ComputerHardwareStoreContracts.ViewModels;
using ComputerHardwareStoreDatabaseImplement.Models;
namespace ComputerHardwareStoreDatabaseImplement.Implements
{
public class CommentStorage : ICommentStorage
{
public List<CommentViewModel> GetFullList()
{
using var context = new ComputerHardwareStoreDBContext();
return context.Comments
.Select(x => x.GetViewModel)
.ToList();
}
public List<CommentViewModel> GetFilteredList(CommentSearchModel model)
{
using var context = new ComputerHardwareStoreDBContext();
return context.Comments
.Select(x => x.GetViewModel)
.ToList();
}
public CommentViewModel? GetElement(CommentSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new ComputerHardwareStoreDBContext();
return context.Comments
.FirstOrDefault(x => x.Id == model.Id)
?.GetViewModel;
}
public CommentViewModel? Insert(CommentBindingModel model)
{
using var context = new ComputerHardwareStoreDBContext();
var newComment = Comment.Create(model);
if (newComment == null)
{
return null;
}
context.Comments.Add(newComment);
context.SaveChanges();
return newComment.GetViewModel;
}
public CommentViewModel? Update(CommentBindingModel model)
{
using var context = new ComputerHardwareStoreDBContext();
var element = context.Comments.FirstOrDefault(x => x.Id == model.Id);
if (element == null)
{
return null;
}
element.Update(model);
context.SaveChanges();
return element.GetViewModel;
}
public CommentViewModel? Delete(CommentBindingModel model)
{
using var context = new ComputerHardwareStoreDBContext();
var element = context.Comments.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Comments.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}