PIBD14-Boyko-M.S.-GSM-Autot.../ProjectGSM/Repositories/Implementations/StatusHistoryRepository.cs

82 lines
3.0 KiB
C#
Raw Normal View History

2024-11-19 00:15:28 +04:00
using System.Data.SqlClient;
using System.Text.Json;
using Dapper;
using Microsoft.Extensions.Logging;
using Npgsql;
using ProjectGSM.Entities;
2024-11-05 03:59:13 +04:00
namespace ProjectGSM.Repositories.Implementations;
public class StatusHistoryRepository : IStatusHistoryRepository
{
2024-11-19 00:15:28 +04:00
private readonly IConnectionString _connectionString;
private readonly ILogger<StatusHistoryRepository> _logger;
public StatusHistoryRepository(IConnectionString connectionString,
ILogger<StatusHistoryRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
2024-11-05 03:59:13 +04:00
public IEnumerable<StatusHistory> ReadStatusHistories(DateTime? dateForm = null, DateTime? dateTo = null,
int? caseId = null, int? statusId = null)
{
2024-11-19 00:15:28 +04:00
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new
NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM status_histories";
var statusHistories =
connection.Query<StatusHistory>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonSerializer.Serialize(statusHistories));
return statusHistories;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
2024-11-05 03:59:13 +04:00
}
public void CreateStatusHistory(StatusHistory statusHistory)
{
2024-11-19 00:15:28 +04:00
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}",
JsonSerializer.Serialize(statusHistory));
try
{
using var connection = new
NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO status_histories (caseid, status, price, createdat)
VALUES (@CaseId, @Status, @Price, @CreatedAt)";
connection.Execute(queryInsert, statusHistory);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
2024-11-05 03:59:13 +04:00
}
public void DeleteStatusHistory(int statusId, int caseId)
{
2024-11-19 00:15:28 +04:00
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Идентификаторы: {statusId}, {caseId}", statusId, caseId);
try
{
using var connection = new
NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"DELETE FROM status_histories WHERE status = @Status AND caseid = @CaseId";
connection.Execute(queryDelete, new { StatusId = statusId, CaseId = caseId });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
2024-11-05 03:59:13 +04:00
}
}