70 lines
2.4 KiB
C#
70 lines
2.4 KiB
C#
using Dapper;
|
|
using GasStation.Entities;
|
|
using Microsoft.Extensions.Logging;
|
|
using Newtonsoft.Json;
|
|
using Npgsql;
|
|
|
|
namespace GasStation.Repositories.Implementations;
|
|
|
|
public class SellingRepository : ISellingRepository
|
|
{
|
|
private readonly IConnectionString _connectionString;
|
|
|
|
private readonly ILogger<SellingRepository> _logger;
|
|
|
|
public SellingRepository(IConnectionString connectionString, ILogger<SellingRepository> logger)
|
|
{
|
|
_connectionString = connectionString;
|
|
_logger = logger;
|
|
}
|
|
|
|
public void CreateSelling(Selling selling)
|
|
{
|
|
_logger.LogInformation("Добавление объекта");
|
|
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(selling));
|
|
|
|
try
|
|
{
|
|
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
|
connection.Open();
|
|
using var transaction = connection.BeginTransaction();
|
|
var queryInsert = @"
|
|
INSERT INTO selling (sellingDateTime, gasmanId)
|
|
VALUES (@SellingDateTime, @GasmanId);
|
|
SELECT MAX(Id) FROM selling";
|
|
var Id = connection.QueryFirst<int>(queryInsert, selling, transaction);
|
|
var querySubInsert = @"
|
|
INSERT INTO product_selling (id, productID, count)
|
|
VALUES (@Id, @ProductID, @Count)";
|
|
foreach (var elem in selling.ProdutcSellings)
|
|
{
|
|
connection.Execute(querySubInsert, new { Id, elem.ProductID, elem.Count }, transaction);
|
|
}
|
|
transaction.Commit();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, "Ошибка при добавлении объекта");
|
|
throw;
|
|
}
|
|
}
|
|
|
|
public IEnumerable<Selling> ReadSelling(DateTime? dateTime = null, int? count = null, int? gasmanID = null)
|
|
{
|
|
_logger.LogInformation("Получение всех объектов");
|
|
try
|
|
{
|
|
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
|
var querySelect = @"SELECT * FROM selling";
|
|
var selling = connection.Query<Selling>(querySelect);
|
|
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(selling));
|
|
return selling;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, "Ошибка при чтении объектов");
|
|
throw;
|
|
}
|
|
}
|
|
}
|