PIbd-22-Ismailov_SUBD/BlogDataModels/BlogDatabaseImplement/Implements/CommentStorage.cs
2023-05-18 21:34:36 +04:00

90 lines
2.8 KiB
C#

using BlogContracts.BindingModel;
using BlogContracts.SearchModels;
using BlogContracts.StorageContracts;
using BlogContracts.ViewModels;
using BlogDatabaseImplement.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlogDatabaseImplement.Implements
{
public class CommentStorage : ICommentStorage
{
public List<CommentViewModel> GetFullList()
{
using var context = new BlogDatabase();
return context.Comments
.Select(x => x.GetViewModel)
.ToList();
}
public List<CommentViewModel> GetFilteredList(CommentSearchModel model)
{
if (string.IsNullOrEmpty(model.Text))
{
return new();
}
using var context = new BlogDatabase();
return context.Comments
.Where(x => x.Text.Contains(model.Text))
.Select(x => x.GetViewModel)
.ToList();
}
public CommentViewModel? GetElement(CommentSearchModel model)
{
if (string.IsNullOrEmpty(model.Text) && !model.Id.HasValue)
{
return null;
}
using var context = new BlogDatabase();
return context.Comments
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.Text) && x.Text == model.Text) ||
(model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public CommentViewModel? Insert(CommentBindingModel model)
{
var newComment = Comment.Create(model);
if (newComment == null)
{
return null;
}
using var context = new BlogDatabase();
context.Comments.Add(newComment);
context.SaveChanges();
return newComment.GetViewModel;
}
public CommentViewModel? Update(CommentBindingModel model)
{
using var context = new BlogDatabase();
var component = context.Comments.FirstOrDefault(x => x.Id == model.Id);
if (component == null)
{
return null;
}
component.Update(model);
context.SaveChanges();
return component.GetViewModel;
}
public CommentViewModel? Delete(CommentBindingModel model)
{
using var context = new BlogDatabase();
var element = context.Comments.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Comments.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}