Files
PIbd-23_Valiullin_R.A_Romashki/Romashki/RomashkiDatabase/Implementations/DiscountStorageContract.cs
2025-04-14 12:06:51 +04:00

62 lines
1.8 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using RomashkiContract.DataModels;
using RomashkiContract.Exceptions;
using RomashkiContract.StoragesContracts;
using RomashkiDatabase.Models;
namespace RomashkiDatabase.Implementations;
internal class DiscountStorageContract : IDiscountStorageContract
{
private readonly RomashkiDbContext _dbContext;
private readonly Mapper _mapper;
public DiscountStorageContract(RomashkiDbContext dbContext)
{
_dbContext = dbContext;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Discount, DiscountDataModel>();
cfg.CreateMap<DiscountDataModel, Discount>();
});
_mapper = new Mapper(config);
}
public List<DiscountDataModel> GetList(DateTime startDate, DateTime endDate, string? buyerId = null)
{
try
{
var query = _dbContext.Discounts.Where(x => x.DiscountDate >= startDate && x.DiscountDate <= endDate);
if (buyerId is not null)
{
query = query.Where(x => x.BuyerId == buyerId);
}
return [.. query.Select(x => _mapper.Map<DiscountDataModel>(x))];
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
public void AddElement(DiscountDataModel discountDataModel)
{
try
{
_dbContext.Discounts.Add(_mapper.Map<Discount>(discountDataModel));
_dbContext.SaveChanges();
}
catch (Exception ex)
{
_dbContext.ChangeTracker.Clear();
throw new StorageException(ex);
}
}
}