60 процентов работы

This commit is contained in:
Сафия Мухамадиева 2024-12-19 04:25:25 +04:00
parent e0f64dbfae
commit fdb6376672
17 changed files with 119 additions and 251 deletions

View File

@ -18,16 +18,4 @@ public class Grades
StudentGrade = studentGrades StudentGrade = studentGrades
}; };
} }
public static Grades CreateEntity(TempStudentGrades tempStudentGrades, IEnumerable<StudentGrades> studentGrades)
{
return new Grades
{
Id = tempStudentGrades.Id,
SubjectsId = tempStudentGrades.SubjectsId,
ProfessorsId = tempStudentGrades.ProfessorsId,
Date = tempStudentGrades.Date,
StudentGrade = studentGrades
};
}
} }

View File

@ -1,18 +0,0 @@
using StudentProgress.Entities.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentProgress.Entities;
public class TempStudentGrades
{
public int Id { get; private set; }
public int SubjectsId { get; private set; }
public int ProfessorsId { get; private set; }
public DateTime Date { get; private set; }
public int StudentID { get; private set; }
public Grade Grade { get; private set; }
}

View File

@ -11,11 +11,11 @@ namespace StudentProgress.Forms
{ {
private readonly IGradesRepository _gradesRepository; private readonly IGradesRepository _gradesRepository;
private readonly ISubjectsRepository _subjectsRepository; private readonly ISubjectsRepository _subjectsRepository;
private readonly IProfessorsNameRepository _professorsRepository; private readonly IProfessorsRepository _professorsRepository;
private readonly IStudentRepository _studentRepository; private readonly IStudentRepository _studentRepository;
public FormGrade(IGradesRepository gradesRepository, ISubjectsRepository subjectsRepository, public FormGrade(IGradesRepository gradesRepository, ISubjectsRepository subjectsRepository,
IProfessorsNameRepository professorsRepository, IStudentRepository studentRepository) IProfessorsRepository professorsRepository, IStudentRepository studentRepository)
{ {
InitializeComponent(); InitializeComponent();
_gradesRepository = gradesRepository ?? throw new ArgumentNullException(nameof(gradesRepository)); _gradesRepository = gradesRepository ?? throw new ArgumentNullException(nameof(gradesRepository));

View File

@ -9,10 +9,10 @@ namespace StudentProgress.Forms
{ {
public partial class FormLecturesCount : Form public partial class FormLecturesCount : Form
{ {
private readonly IProfessorsNameRepository _professorsRepository; private readonly IProfessorsRepository _professorsRepository;
private readonly ILecturesRepository _lecturesRepository; private readonly ILecturesRepository _lecturesRepository;
public FormLecturesCount(IProfessorsNameRepository professorsRepository, ILecturesRepository lecturesRepository) public FormLecturesCount(IProfessorsRepository professorsRepository, ILecturesRepository lecturesRepository)
{ {
InitializeComponent(); InitializeComponent();
_professorsRepository = professorsRepository; _professorsRepository = professorsRepository;

View File

@ -8,7 +8,7 @@ namespace StudentProgress.Forms
{ {
public partial class FormProfessor : Form public partial class FormProfessor : Form
{ {
private readonly IProfessorsNameRepository _professorsRepository; private readonly IProfessorsRepository _professorsRepository;
private int? _professorId; private int? _professorId;
public int Id public int Id
@ -34,7 +34,7 @@ namespace StudentProgress.Forms
} }
} }
public FormProfessor(IProfessorsNameRepository professorsRepository) public FormProfessor(IProfessorsRepository professorsRepository)
{ {
InitializeComponent(); InitializeComponent();
_professorsRepository = professorsRepository ?? throw new ArgumentNullException(nameof(professorsRepository)); _professorsRepository = professorsRepository ?? throw new ArgumentNullException(nameof(professorsRepository));

View File

@ -8,9 +8,9 @@ namespace StudentProgress.Forms
public partial class FormProfessors : Form public partial class FormProfessors : Form
{ {
private readonly IUnityContainer _container; private readonly IUnityContainer _container;
private readonly IProfessorsNameRepository _professorsRepository; private readonly IProfessorsRepository _professorsRepository;
public FormProfessors(IUnityContainer container, IProfessorsNameRepository professorsRepository) public FormProfessors(IUnityContainer container, IProfessorsRepository professorsRepository)
{ {
InitializeComponent(); InitializeComponent();
_container = container ?? throw new ArgumentNullException(nameof(container)); _container = container ?? throw new ArgumentNullException(nameof(container));

View File

@ -7,10 +7,10 @@ namespace StudentProgress.Forms
{ {
public partial class FormRecordLecture : Form public partial class FormRecordLecture : Form
{ {
private readonly IProfessorsNameRepository _professorsRepository; private readonly IProfessorsRepository _professorsRepository;
private readonly ILecturesRepository _lecturesRepository; private readonly ILecturesRepository _lecturesRepository;
public FormRecordLecture(IProfessorsNameRepository professorsRepository, ILecturesRepository lecturesRepository) public FormRecordLecture(IProfessorsRepository professorsRepository, ILecturesRepository lecturesRepository)
{ {
InitializeComponent(); InitializeComponent();
_professorsRepository = professorsRepository; _professorsRepository = professorsRepository;

View File

@ -42,7 +42,7 @@ namespace StudentProgress
container.RegisterType<IGradesRepository, GradesRepository>(new TransientLifetimeManager()); container.RegisterType<IGradesRepository, GradesRepository>(new TransientLifetimeManager());
container.RegisterType<IGroupRepository, GroupRepository>(new TransientLifetimeManager()); container.RegisterType<IGroupRepository, GroupRepository>(new TransientLifetimeManager());
container.RegisterType<ILecturesRepository, LecturesRepository>(new TransientLifetimeManager()); container.RegisterType<ILecturesRepository, LecturesRepository>(new TransientLifetimeManager());
container.RegisterType<IProfessorsNameRepository, ProfessorsNameRepository>(new TransientLifetimeManager()); container.RegisterType<IProfessorsRepository, ProfessorsRepository>(new TransientLifetimeManager());
container.RegisterType<IStudentRepository, StudentRepository>(new TransientLifetimeManager()); container.RegisterType<IStudentRepository, StudentRepository>(new TransientLifetimeManager());
container.RegisterType<ISubjectsRepository, SubjectsRepository>(new TransientLifetimeManager()); container.RegisterType<ISubjectsRepository, SubjectsRepository>(new TransientLifetimeManager());

View File

@ -1,13 +0,0 @@
using StudentProgress.Entities;
using System.Collections.Generic;
namespace StudentProgress.Repositories;
public interface IProfessorsNameRepository
{
IEnumerable<Professors> ReadProfessorsName();
Professors ReadProfessorsNameById(int id);
void CreateProfessorsName(Professors professorsName);
void UpdateProfessorsName(Professors professorsName);
void DeleteProfessorsName(int id);
}

View File

@ -0,0 +1,13 @@
using StudentProgress.Entities;
using System.Collections.Generic;
namespace StudentProgress.Repositories;
public interface IProfessorsRepository
{
IEnumerable<Professors> ReadProfessors();
Professors ReadProfessorsById(int id);
void CreateProfessors(Professors professors);
void UpdateProfessors(Professors professors);
void DeleteProfessors(int id);
}

View File

@ -5,5 +5,5 @@ namespace StudentProgress.Repositories.Implementations;
public class ConnectionString : IConnectionString public class ConnectionString : IConnectionString
{ {
string IConnectionString.ConnectionString => string IConnectionString.ConnectionString =>
"Host=localhost;Port=5432;Database=postgres;Username=postgres;Password=Ildan12345;"; "Host=localhost;Port=5432;Database=OTP_sophiya;Username=postgres;Password=030405;";
} }

View File

@ -1,11 +1,8 @@
using Dapper; using Dapper;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Newtonsoft.Json; using Newtonsoft.Json;
using Npgsql;
using StudentProgress.Entities; using StudentProgress.Entities;
using StudentProgress.Repositories;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
namespace StudentProgress.Repositories.Implementations namespace StudentProgress.Repositories.Implementations
{ {
@ -26,11 +23,28 @@ namespace StudentProgress.Repositories.Implementations
_logger.LogDebug("Оценка: {json}", JsonConvert.SerializeObject(grade)); _logger.LogDebug("Оценка: {json}", JsonConvert.SerializeObject(grade));
try try
{ {
using var connection = new SqlConnection(_connectionString.ConnectionString); using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var query = @" connection.Open();
using var transaction = connection.BeginTransaction();
var queryInsert = @"
INSERT INTO Grades (SubjectsId, ProfessorsId, Date) INSERT INTO Grades (SubjectsId, ProfessorsId, Date)
VALUES (@SubjectsId, @ProfessorsId, @Date)"; VALUES (@SubjectsId, @ProfessorsId, @Date);
connection.Execute(query, grade); SELECT MAX(Id) FROM Grades";
var gradesId =
connection.QueryFirst<int>(queryInsert, grade, transaction);
var querySubInsert = @"
INSERT INTO StudentGrades (StudentID, Grade, GradesId)
VALUES (@StudentID, @Grade, @GradesId)";
foreach (var elem in grade.StudentGrade)
{
connection.Execute(querySubInsert, new
{
elem.StudentID,
elem.Grade,
gradesId,
}, transaction);
}
transaction.Commit();
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -45,7 +59,7 @@ namespace StudentProgress.Repositories.Implementations
_logger.LogDebug("Оценка: {id}", id); _logger.LogDebug("Оценка: {id}", id);
try try
{ {
using var connection = new SqlConnection(_connectionString.ConnectionString); using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var query = "DELETE FROM Grades WHERE Id = @Id"; var query = "DELETE FROM Grades WHERE Id = @Id";
connection.Execute(query, new { Id = id }); connection.Execute(query, new { Id = id });
} }
@ -61,32 +75,10 @@ namespace StudentProgress.Repositories.Implementations
_logger.LogInformation("Получение оценок"); _logger.LogInformation("Получение оценок");
try try
{ {
using var connection = new SqlConnection(_connectionString.ConnectionString); using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var query = "SELECT * FROM Grades"; var query = "SELECT * FROM Grades";
var parameters = new DynamicParameters();
if (dateFrom.HasValue) var grades = connection.Query<Grades>(query);
{
query += " WHERE Date >= @DateFrom";
parameters.Add("DateFrom", dateFrom.Value);
}
if (dateTo.HasValue)
{
query += " AND Date <= @DateTo";
parameters.Add("DateTo", dateTo.Value);
}
if (subjectsId.HasValue)
{
query += " AND SubjectsId = @SubjectsId";
parameters.Add("SubjectsId", subjectsId.Value);
}
if (professorsId.HasValue)
{
query += " AND ProfessorsId = @ProfessorsId";
parameters.Add("ProfessorsId", professorsId.Value);
}
var grades = connection.Query<Grades>(query, parameters);
_logger.LogDebug("Полученные оценки: {json}", JsonConvert.SerializeObject(grades)); _logger.LogDebug("Полученные оценки: {json}", JsonConvert.SerializeObject(grades));
return grades; return grades;
} }
@ -96,25 +88,5 @@ namespace StudentProgress.Repositories.Implementations
throw; throw;
} }
} }
public void UpdateGrade(Grades grade)
{
_logger.LogInformation("Редактирование оценки");
_logger.LogDebug("Оценка: {json}", JsonConvert.SerializeObject(grade));
try
{
using var connection = new SqlConnection(_connectionString.ConnectionString);
var query = @"
UPDATE Grades
SET SubjectsId = @SubjectsId, ProfessorsId = @ProfessorsId, Date = @Date
WHERE Id = @Id";
connection.Execute(query, grade);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании оценки");
throw;
}
}
} }
} }

View File

@ -25,8 +25,8 @@ public class GroupRepository : IGroupRepository
try try
{ {
using var connection = new NpgsqlConnection(_connectionString.ConnectionString); using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"INSERT INTO Groups (NameGroup, Course, NameFaculty) var queryInsert = @"INSERT INTO ""Group"" (NameGroup)
VALUES (@NameGroup, @Course, @NameFaculty)"; VALUES (@NameGroup)";
connection.Execute(queryInsert, group); connection.Execute(queryInsert, group);
} }
catch (Exception ex) catch (Exception ex)
@ -44,7 +44,7 @@ VALUES (@NameGroup, @Course, @NameFaculty)";
{ {
using var connection = new NpgsqlConnection(_connectionString.ConnectionString); using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @" var queryDelete = @"
DELETE FROM Groups DELETE FROM ""Group""
WHERE Id=@id"; WHERE Id=@id";
connection.Execute(queryDelete, new { id }); connection.Execute(queryDelete, new { id });
} }
@ -61,7 +61,7 @@ WHERE Id=@id";
try try
{ {
using var connection = new NpgsqlConnection(_connectionString.ConnectionString); using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Groups"; var querySelect = "SELECT * FROM \"Group\"";
var groups = connection.Query<Group>(querySelect); var groups = connection.Query<Group>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", _logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(groups)); JsonConvert.SerializeObject(groups));
@ -82,7 +82,7 @@ WHERE Id=@id";
{ {
using var connection = new NpgsqlConnection(_connectionString.ConnectionString); using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @" var querySelect = @"
SELECT * FROM Groups SELECT * FROM ""Group""
WHERE Id=@id"; WHERE Id=@id";
var group = connection.QueryFirst<Group>(querySelect, new var group = connection.QueryFirst<Group>(querySelect, new
{ {
@ -109,11 +109,9 @@ WHERE Id=@id";
{ {
using var connection = new NpgsqlConnection(_connectionString.ConnectionString); using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @" var queryUpdate = @"
UPDATE Groups UPDATE ""Group""
SET SET
NameGroup=@NameGroup, NameGroup=@NameGroup
Course=@Course,
NameFaculty=@NameFaculty
WHERE Id=@Id"; WHERE Id=@Id";
connection.Execute(queryUpdate, group); connection.Execute(queryUpdate, group);
} }

View File

@ -1,11 +1,8 @@
using Dapper; using Dapper;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Newtonsoft.Json; using Newtonsoft.Json;
using Npgsql;
using StudentProgress.Entities; using StudentProgress.Entities;
using StudentProgress.Repositories;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
namespace StudentProgress.Repositories.Implementations namespace StudentProgress.Repositories.Implementations
{ {
@ -25,7 +22,7 @@ namespace StudentProgress.Repositories.Implementations
_logger.LogInformation("Получение лекций"); _logger.LogInformation("Получение лекций");
try try
{ {
using var connection = new SqlConnection(_connectionString.ConnectionString); using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var query = "SELECT * FROM Lectures"; var query = "SELECT * FROM Lectures";
var lectures = connection.Query<Lectures>(query); var lectures = connection.Query<Lectures>(query);
_logger.LogDebug("Полученные лекции: {json}", JsonConvert.SerializeObject(lectures)); _logger.LogDebug("Полученные лекции: {json}", JsonConvert.SerializeObject(lectures));
@ -44,9 +41,9 @@ namespace StudentProgress.Repositories.Implementations
_logger.LogDebug("Лекция: {json}", JsonConvert.SerializeObject(lecture)); _logger.LogDebug("Лекция: {json}", JsonConvert.SerializeObject(lecture));
try try
{ {
using var connection = new SqlConnection(_connectionString.ConnectionString); using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var query = @" var query = @"
INSERT INTO Lectures (ProfessorId, Date, Auditorium) INSERT INTO Lectures (ProfessorsId, Date, Auditorium)
VALUES (@ProfessorsId, @Date, @Auditorium)"; VALUES (@ProfessorsId, @Date, @Auditorium)";
connection.Execute(query, lecture); connection.Execute(query, lecture);
} }
@ -63,8 +60,8 @@ namespace StudentProgress.Repositories.Implementations
_logger.LogDebug("Лекция: {id}", lectureId); _logger.LogDebug("Лекция: {id}", lectureId);
try try
{ {
using var connection = new SqlConnection(_connectionString.ConnectionString); using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var query = "DELETE FROM Lectures WHERE LectureId = @LectureId"; var query = "DELETE FROM Lectures WHERE Id = @LectureId";
connection.Execute(query, new { LectureId = lectureId }); connection.Execute(query, new { LectureId = lectureId });
} }
catch (Exception ex) catch (Exception ex)

View File

@ -3,33 +3,31 @@ using Microsoft.Extensions.Logging;
using Newtonsoft.Json; using Newtonsoft.Json;
using Npgsql; using Npgsql;
using StudentProgress.Entities; using StudentProgress.Entities;
using StudentProgress.Repositories;
using System.Data.SqlClient;
namespace StudentProgress.Repositories.Implementations; namespace StudentProgress.Repositories.Implementations;
public class ProfessorsNameRepository : IProfessorsNameRepository public class ProfessorsRepository : IProfessorsRepository
{ {
private readonly IConnectionString _connectionString; private readonly IConnectionString _connectionString;
private readonly ILogger<ProfessorsNameRepository> _logger; private readonly ILogger<ProfessorsRepository> _logger;
public ProfessorsNameRepository(IConnectionString connectionString, ILogger<ProfessorsNameRepository> logger) public ProfessorsRepository(IConnectionString connectionString, ILogger<ProfessorsRepository> logger)
{ {
_connectionString = connectionString; _connectionString = connectionString;
_logger = logger; _logger = logger;
} }
public void CreateProfessorsName(Professors professorsName) public void CreateProfessors(Professors professors)
{ {
_logger.LogInformation("Добавление объекта"); _logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(professorsName)); _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(professors));
try try
{ {
using var connection = new NpgsqlConnection(_connectionString.ConnectionString); using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"INSERT INTO ProfessorsName (FirstName, LastName, MiddleName, Classes) var queryInsert = @"INSERT INTO Professors (FirstName, Surname)
VALUES (@FirstName, @LastName, @MiddleName, @Classes)"; VALUES (@FirstName, @Surname)";
connection.Execute(queryInsert, professorsName); connection.Execute(queryInsert, professors);
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -38,15 +36,14 @@ VALUES (@FirstName, @LastName, @MiddleName, @Classes)";
} }
} }
public void DeleteProfessorsName(int id) public void DeleteProfessors(int id)
{ {
_logger.LogInformation("Удаление объекта"); _logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id); _logger.LogDebug("Объект: {id}", id);
try try
{ {
using var connection = new NpgsqlConnection(_connectionString.ConnectionString); using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @" var queryDelete = @"DELETE FROM Professors
DELETE FROM ProfessorsName
WHERE Id=@id"; WHERE Id=@id";
connection.Execute(queryDelete, new { id }); connection.Execute(queryDelete, new { id });
} }
@ -57,17 +54,17 @@ WHERE Id=@id";
} }
} }
public IEnumerable<Professors> ReadProfessorsName() public IEnumerable<Professors> ReadProfessors()
{ {
_logger.LogInformation("Получение всех объектов"); _logger.LogInformation("Получение всех объектов");
try try
{ {
using var connection = new NpgsqlConnection(_connectionString.ConnectionString); using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM ProfessorsName"; var querySelect = "SELECT * FROM Professors";
var professorsNames = connection.Query<Professors>(querySelect); var professors = connection.Query<Professors>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", _logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(professorsNames)); JsonConvert.SerializeObject(professors));
return professorsNames; return professors;
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -76,7 +73,7 @@ WHERE Id=@id";
} }
} }
public Professors ReadProfessorsNameById(int id) public Professors ReadProfessorsById(int id)
{ {
_logger.LogInformation("Получение объекта по идентификатору"); _logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id); _logger.LogDebug("Объект: {id}", id);
@ -84,13 +81,13 @@ WHERE Id=@id";
{ {
using var connection = new NpgsqlConnection(_connectionString.ConnectionString); using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @" var querySelect = @"
SELECT * FROM ProfessorsName SELECT * FROM Professors
WHERE Id=@id"; WHERE Id=@id";
var professorsName = connection.QueryFirst<Professors>(querySelect, new { id }); var professors = connection.QueryFirst<Professors>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", _logger.LogDebug("Найденный объект: {json}",
JsonConvert.SerializeObject(professorsName)); JsonConvert.SerializeObject(professors));
return professorsName; return professors;
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -99,7 +96,7 @@ WHERE Id=@id";
} }
} }
public void UpdateProfessorsName(Professors professorsName) public void UpdateProfessors(Professors professorsName)
{ {
_logger.LogInformation("Редактирование объекта"); _logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", _logger.LogDebug("Объект: {json}",
@ -108,12 +105,10 @@ WHERE Id=@id";
{ {
using var connection = new NpgsqlConnection(_connectionString.ConnectionString); using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @" var queryUpdate = @"
UPDATE ProfessorsName UPDATE Professors
SET SET
FirstName=@FirstName, FirstName=@FirstName,
LastName=@LastName, Surname=@Surname
MiddleName=@MiddleName,
Classes=@Classes
WHERE Id=@Id"; WHERE Id=@Id";
connection.Execute(queryUpdate, professorsName); connection.Execute(queryUpdate, professorsName);
} }

View File

@ -28,8 +28,8 @@ public class StudentRepository : IStudentRepository
{ {
using var connection = new NpgsqlConnection(_connectionString.ConnectionString); using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @" var queryInsert = @"
INSERT INTO Student (FirstName, LastName, MiddleName, Phone, GroupID) INSERT INTO Student (Name, Surname, GroupId)
VALUES (@FirstName, @LastName, @MiddleName, @Phone, @GroupID)"; VALUES (@Name, @Surname, @GroupId)";
connection.Execute(queryInsert, student); connection.Execute(queryInsert, student);
} }
catch (Exception ex) catch (Exception ex)
@ -113,11 +113,9 @@ WHERE Id=@id";
var queryUpdate = @" var queryUpdate = @"
UPDATE Student UPDATE Student
SET SET
FirstName=@FirstName, Name=@Name,
LastName=@LastName, Surname=@Surname,
MiddleName=@MiddleName, GroupId=@GroupId
Phone=@Phone,
GroupID=@GroupID
WHERE Id=@Id"; WHERE Id=@Id";
connection.Execute(queryUpdate, student); connection.Execute(queryUpdate, student);
} }

View File

@ -17,28 +17,17 @@ namespace StudentProgress.Repositories.Implementations
_logger = logger; _logger = logger;
} }
// Добавление нового предмета
public void CreateSubjects_(Subjects subject) public void CreateSubjects_(Subjects subject)
{ {
_logger.LogInformation("Добавление объекта"); _logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(subject)); _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(subject));
try try
{ {
using var connection = new NpgsqlConnection(_connectionString.ConnectionString); using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open(); var queryInsert = @"INSERT INTO Subjects (NameSubject, Course)
using var transaction = connection.BeginTransaction(); VALUES (@NameSubject, @Course)";
connection.Execute(queryInsert, subject);
var queryInsert = @"
INSERT INTO Subject (NameSubject)
VALUES (@NameSubject);
SELECT MAX(Id) FROM Subject";
// Выполняем запрос и получаем ID созданного предмета
var subjectId = connection.QueryFirst<int>(queryInsert, subject, transaction);
transaction.Commit();
_logger.LogInformation("Успешно добавлен объект с Id: {id}", subjectId);
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -47,7 +36,6 @@ SELECT MAX(Id) FROM Subject";
} }
} }
// Удаление предмета по идентификатору
public void DeleteSubjects(int id) public void DeleteSubjects(int id)
{ {
_logger.LogInformation("Удаление объекта"); _logger.LogInformation("Удаление объекта");
@ -55,20 +43,9 @@ SELECT MAX(Id) FROM Subject";
try try
{ {
using var connection = new NpgsqlConnection(_connectionString.ConnectionString); using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @" var queryDelete = @"DELETE FROM Subjects
DELETE FROM Subject WHERE Id=@id";
WHERE Id=@Id"; connection.Execute(queryDelete, new { id });
var rowsAffected = connection.Execute(queryDelete, new { Id = id });
if (rowsAffected == 0)
{
_logger.LogWarning("Объект с Id: {id} не найден для удаления", id);
}
else
{
_logger.LogInformation("Объект с Id: {id} успешно удалён", id);
}
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -77,45 +54,18 @@ WHERE Id=@Id";
} }
} }
// Получение всех предметов
public IEnumerable<Subjects> ReadSubjects(int? id = null) public IEnumerable<Subjects> ReadSubjects(int? id = null)
{ {
_logger.LogInformation("Получение объектов"); _logger.LogInformation("Получение всех объектов");
try try
{ {
using var connection = new NpgsqlConnection(_connectionString.ConnectionString); using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Subjects";
if (id.HasValue) var subjects = connection.Query<Subjects>(querySelect);
{ _logger.LogDebug("Полученные объекты: {json}",
// Если указан ID, возвращаем конкретный предмет JsonConvert.SerializeObject(subjects));
var querySelectById = @"
SELECT * FROM Subject
WHERE Id = @Id";
var subject = connection.Query<Subjects>(querySelectById, new { Id = id.Value }).ToList();
if (!subject.Any())
{
_logger.LogWarning("Объект с Id: {id} не найден", id);
}
else
{
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(subject));
}
return subject;
}
else
{
// Если ID не указан, возвращаем все предметы
var querySelectAll = @"SELECT * FROM Subject";
var subjects = connection.Query<Subjects>(querySelectAll).ToList();
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(subjects));
return subjects; return subjects;
} }
}
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Ошибка при чтении объектов"); _logger.LogError(ex, "Ошибка при чтении объектов");
@ -123,7 +73,6 @@ WHERE Id = @Id";
} }
} }
// Получение предмета по идентификатору
public Subjects ReadSubjectById(int id) public Subjects ReadSubjectById(int id)
{ {
_logger.LogInformation("Получение объекта по идентификатору"); _logger.LogInformation("Получение объекта по идентификатору");
@ -131,21 +80,11 @@ WHERE Id = @Id";
try try
{ {
using var connection = new NpgsqlConnection(_connectionString.ConnectionString); using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @" var querySelect = @"SELECT * FROM Subjects
SELECT * FROM Subject WHERE Id=@id";
WHERE Id = @Id"; var subject = connection.QueryFirst<Subjects>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}",
var subject = connection.QueryFirstOrDefault<Subjects>(querySelect, new { Id = id }); JsonConvert.SerializeObject(subject));
if (subject == null)
{
_logger.LogWarning("Объект с Id: {id} не найден", id);
}
else
{
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(subject));
}
return subject; return subject;
} }
catch (Exception ex) catch (Exception ex)
@ -155,7 +94,6 @@ WHERE Id = @Id";
} }
} }
// Обновление данных предмета
public void UpdateSubject(Subjects subject) public void UpdateSubject(Subjects subject)
{ {
_logger.LogInformation("Редактирование объекта"); _logger.LogInformation("Редактирование объекта");
@ -166,11 +104,11 @@ WHERE Id = @Id";
connection.Open(); connection.Open();
using var transaction = connection.BeginTransaction(); using var transaction = connection.BeginTransaction();
var queryUpdate = @" var queryUpdate = @"UPDATE Subjects
UPDATE Subject SET
SET NameSubject = @NameSubject NameSubject = @NameSubject,
Course = @Course
WHERE Id = @Id"; WHERE Id = @Id";
connection.Execute(queryUpdate, subject, transaction); connection.Execute(queryUpdate, subject, transaction);
transaction.Commit(); transaction.Commit();