Files
PIBD-23_Coursach_YouAreProg…/YouAreProgrammerShop/YAPDatabase/Implementations/CommentStorageContract.cs

129 lines
4.0 KiB
C#

using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Npgsql;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using YAPContracts.DataModels;
using YAPContracts.Exceptions;
using YAPContracts.StorageContracts;
using YAPDatabase.Models;
namespace YAPDatabase.Implementations
{
internal class CommentStorageContract : ICommentStorageContract
{
private readonly YAPDbContext _dbContext;
private readonly Mapper _mapper;
public CommentStorageContract(YAPDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Comment, CommentDataModel>();
cfg.CreateMap<CommentDataModel, Comment>();
});
_mapper = new Mapper(config);
}
public void AddElement(CommentDataModel comment)
{
try
{
_dbContext.Comments.Add(_mapper.Map<Comment>(comment));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void UpdateElement(CommentDataModel comment)
{
try
{
var newComment = GetCommentById(comment.Id) ?? throw new ElementNotFoundException(comment.Id);
_dbContext.Comments.Update(_mapper.Map(comment, newComment));
_dbContext.SaveChanges();
}
catch (ElementNotFoundException)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void DeleteElement(string id)
{
try
{
var comment = GetCommentById(id) ?? throw new ElementNotFoundException(id);
_dbContext.Comments.Remove(comment);
_dbContext.SaveChanges();
}
catch (ElementNotFoundException ex)
{
_dbContext.ChangeTracker.Clear();
throw;
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public CommentDataModel? GetElementById(string id)
{
try
{
return _mapper.Map<CommentDataModel>(GetCommentById(id));
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public List<CommentDataModel> GetList(DateTime? fromDate = null, DateTime? toDate = null, string? userId = null, string? productSetId = null)
{
try
{
var query = _dbContext.Comments.AsQueryable();
if (fromDate is not null && toDate is not null)
{
query = query.Where(x => x.CommentDate >= fromDate && x.CommentDate < toDate);
}
if (userId is not null)
{
query = query.Where(x => x.UserId == userId);
}
if (productSetId is not null)
{
query = query.Where(x => x.ProductSetId == productSetId);
}
return [.. query.Select(x => _mapper.Map<CommentDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
private Comment? GetCommentById(string id) => _dbContext.Comments.FirstOrDefault(x => x.Id == id);
}
}