76 lines
2.6 KiB
C#
76 lines
2.6 KiB
C#
using Dapper;
|
|
using Microsoft.Extensions.Logging;
|
|
using Newtonsoft.Json;
|
|
using Npgsql;
|
|
using ProjectFuel.Entities;
|
|
using ProjectFuel.Repositories;
|
|
|
|
namespace ProjectFuel.Repositories.Implementations;
|
|
|
|
public class TripRepository : ITripRepository
|
|
{
|
|
private readonly IConnectionString _connectionString;
|
|
|
|
private readonly ILogger<TripRepository> _logger;
|
|
|
|
public TripRepository(IConnectionString connectionString, ILogger<TripRepository> logger)
|
|
{
|
|
_connectionString = connectionString;
|
|
_logger = logger;
|
|
}
|
|
public void CreateTrip(Trip trip)
|
|
{
|
|
_logger.LogInformation("Добавление объекта");
|
|
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(trip));
|
|
|
|
try
|
|
{
|
|
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
|
connection.Open();
|
|
using var transaction = connection.BeginTransaction();
|
|
var queryInsert = @"
|
|
INSERT INTO Trip (Start_Date, End_Date, Shift, Fuel_Consumption, Car_ID, Driver_ID)
|
|
VALUES (@Start_Date, @End_Date, @Shift, @Fuel_Consumption, @Car_ID, @Driver_ID);
|
|
SELECT MAX(Trip_ID) FROM Trip";
|
|
var tripId = connection.QueryFirst<int>(queryInsert, trip, transaction);
|
|
var querySubInsert = @"
|
|
INSERT INTO Trip_Route (Trip_ID, Route_ID)
|
|
VALUES (@tripId, @Route_ID)";
|
|
foreach (var elem in trip.Routes)
|
|
{
|
|
connection.Execute(querySubInsert, new
|
|
{
|
|
tripId,
|
|
elem.Route_ID
|
|
}, transaction);
|
|
}
|
|
transaction.Commit();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, "Ошибка при добавлении объекта");
|
|
throw;
|
|
}
|
|
}
|
|
|
|
|
|
public IEnumerable<Trip> ReadTrips(DateTime? dateFrom = null, DateTime? dateTo = null, int? carId = null, int? driverId = null, int? routeId = null)
|
|
{
|
|
_logger.LogInformation("Получение всех объектов");
|
|
try
|
|
{
|
|
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
|
var querySelect = "SELECT * FROM Trip";
|
|
var trips = connection.Query<Trip>(querySelect);
|
|
_logger.LogDebug("Полученные объекты: {json}",
|
|
JsonConvert.SerializeObject(trips));
|
|
return trips;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, "Ошибка при чтении объектов");
|
|
throw;
|
|
}
|
|
}
|
|
}
|