diff --git a/StudentProgress/StudentProgress/Entities/Grades.cs b/StudentProgress/StudentProgress/Entities/Grades.cs index 7b89070..c9c4e58 100644 --- a/StudentProgress/StudentProgress/Entities/Grades.cs +++ b/StudentProgress/StudentProgress/Entities/Grades.cs @@ -18,16 +18,4 @@ public class Grades StudentGrade = studentGrades }; } - - public static Grades CreateEntity(TempStudentGrades tempStudentGrades, IEnumerable studentGrades) - { - return new Grades - { - Id = tempStudentGrades.Id, - SubjectsId = tempStudentGrades.SubjectsId, - ProfessorsId = tempStudentGrades.ProfessorsId, - Date = tempStudentGrades.Date, - StudentGrade = studentGrades - }; - } } diff --git a/StudentProgress/StudentProgress/Entities/TempStudentGrades.cs b/StudentProgress/StudentProgress/Entities/TempStudentGrades.cs deleted file mode 100644 index c6d6b18..0000000 --- a/StudentProgress/StudentProgress/Entities/TempStudentGrades.cs +++ /dev/null @@ -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; } -} diff --git a/StudentProgress/StudentProgress/Forms/FormGrade.cs b/StudentProgress/StudentProgress/Forms/FormGrade.cs index 3f43ae9..6feea54 100644 --- a/StudentProgress/StudentProgress/Forms/FormGrade.cs +++ b/StudentProgress/StudentProgress/Forms/FormGrade.cs @@ -11,11 +11,11 @@ namespace StudentProgress.Forms { private readonly IGradesRepository _gradesRepository; private readonly ISubjectsRepository _subjectsRepository; - private readonly IProfessorsNameRepository _professorsRepository; + private readonly IProfessorsRepository _professorsRepository; private readonly IStudentRepository _studentRepository; public FormGrade(IGradesRepository gradesRepository, ISubjectsRepository subjectsRepository, - IProfessorsNameRepository professorsRepository, IStudentRepository studentRepository) + IProfessorsRepository professorsRepository, IStudentRepository studentRepository) { InitializeComponent(); _gradesRepository = gradesRepository ?? throw new ArgumentNullException(nameof(gradesRepository)); diff --git a/StudentProgress/StudentProgress/Forms/FormLecturesCount.cs b/StudentProgress/StudentProgress/Forms/FormLecturesCount.cs index c9fe297..f677e16 100644 --- a/StudentProgress/StudentProgress/Forms/FormLecturesCount.cs +++ b/StudentProgress/StudentProgress/Forms/FormLecturesCount.cs @@ -9,10 +9,10 @@ namespace StudentProgress.Forms { public partial class FormLecturesCount : Form { - private readonly IProfessorsNameRepository _professorsRepository; + private readonly IProfessorsRepository _professorsRepository; private readonly ILecturesRepository _lecturesRepository; - public FormLecturesCount(IProfessorsNameRepository professorsRepository, ILecturesRepository lecturesRepository) + public FormLecturesCount(IProfessorsRepository professorsRepository, ILecturesRepository lecturesRepository) { InitializeComponent(); _professorsRepository = professorsRepository; diff --git a/StudentProgress/StudentProgress/Forms/FormProfesor.cs b/StudentProgress/StudentProgress/Forms/FormProfesor.cs index 51b5532..3a22601 100644 --- a/StudentProgress/StudentProgress/Forms/FormProfesor.cs +++ b/StudentProgress/StudentProgress/Forms/FormProfesor.cs @@ -8,7 +8,7 @@ namespace StudentProgress.Forms { public partial class FormProfessor : Form { - private readonly IProfessorsNameRepository _professorsRepository; + private readonly IProfessorsRepository _professorsRepository; private int? _professorId; public int Id @@ -34,7 +34,7 @@ namespace StudentProgress.Forms } } - public FormProfessor(IProfessorsNameRepository professorsRepository) + public FormProfessor(IProfessorsRepository professorsRepository) { InitializeComponent(); _professorsRepository = professorsRepository ?? throw new ArgumentNullException(nameof(professorsRepository)); diff --git a/StudentProgress/StudentProgress/Forms/FormProfessors.cs b/StudentProgress/StudentProgress/Forms/FormProfessors.cs index caa8a76..e404747 100644 --- a/StudentProgress/StudentProgress/Forms/FormProfessors.cs +++ b/StudentProgress/StudentProgress/Forms/FormProfessors.cs @@ -8,9 +8,9 @@ namespace StudentProgress.Forms public partial class FormProfessors : Form { 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(); _container = container ?? throw new ArgumentNullException(nameof(container)); diff --git a/StudentProgress/StudentProgress/Forms/FormRecordLecture.cs b/StudentProgress/StudentProgress/Forms/FormRecordLecture.cs index cfe2fad..be45bc4 100644 --- a/StudentProgress/StudentProgress/Forms/FormRecordLecture.cs +++ b/StudentProgress/StudentProgress/Forms/FormRecordLecture.cs @@ -7,10 +7,10 @@ namespace StudentProgress.Forms { public partial class FormRecordLecture : Form { - private readonly IProfessorsNameRepository _professorsRepository; + private readonly IProfessorsRepository _professorsRepository; private readonly ILecturesRepository _lecturesRepository; - public FormRecordLecture(IProfessorsNameRepository professorsRepository, ILecturesRepository lecturesRepository) + public FormRecordLecture(IProfessorsRepository professorsRepository, ILecturesRepository lecturesRepository) { InitializeComponent(); _professorsRepository = professorsRepository; diff --git a/StudentProgress/StudentProgress/Program.cs b/StudentProgress/StudentProgress/Program.cs index 45f1fcb..000fa72 100644 --- a/StudentProgress/StudentProgress/Program.cs +++ b/StudentProgress/StudentProgress/Program.cs @@ -42,7 +42,7 @@ namespace StudentProgress container.RegisterType(new TransientLifetimeManager()); container.RegisterType(new TransientLifetimeManager()); container.RegisterType(new TransientLifetimeManager()); - container.RegisterType(new TransientLifetimeManager()); + container.RegisterType(new TransientLifetimeManager()); container.RegisterType(new TransientLifetimeManager()); container.RegisterType(new TransientLifetimeManager()); diff --git a/StudentProgress/StudentProgress/Repositories/IProfessorsNameRepository.cs b/StudentProgress/StudentProgress/Repositories/IProfessorsNameRepository.cs deleted file mode 100644 index 672d629..0000000 --- a/StudentProgress/StudentProgress/Repositories/IProfessorsNameRepository.cs +++ /dev/null @@ -1,13 +0,0 @@ -using StudentProgress.Entities; -using System.Collections.Generic; - -namespace StudentProgress.Repositories; - -public interface IProfessorsNameRepository -{ - IEnumerable ReadProfessorsName(); - Professors ReadProfessorsNameById(int id); - void CreateProfessorsName(Professors professorsName); - void UpdateProfessorsName(Professors professorsName); - void DeleteProfessorsName(int id); -} \ No newline at end of file diff --git a/StudentProgress/StudentProgress/Repositories/IProfessorsRepository.cs b/StudentProgress/StudentProgress/Repositories/IProfessorsRepository.cs new file mode 100644 index 0000000..d3e6b54 --- /dev/null +++ b/StudentProgress/StudentProgress/Repositories/IProfessorsRepository.cs @@ -0,0 +1,13 @@ +using StudentProgress.Entities; +using System.Collections.Generic; + +namespace StudentProgress.Repositories; + +public interface IProfessorsRepository +{ + IEnumerable ReadProfessors(); + Professors ReadProfessorsById(int id); + void CreateProfessors(Professors professors); + void UpdateProfessors(Professors professors); + void DeleteProfessors(int id); +} \ No newline at end of file diff --git a/StudentProgress/StudentProgress/Repositories/Implementations/ConnectionString.cs b/StudentProgress/StudentProgress/Repositories/Implementations/ConnectionString.cs index 850be20..d6b5363 100644 --- a/StudentProgress/StudentProgress/Repositories/Implementations/ConnectionString.cs +++ b/StudentProgress/StudentProgress/Repositories/Implementations/ConnectionString.cs @@ -5,5 +5,5 @@ namespace StudentProgress.Repositories.Implementations; public class ConnectionString : IConnectionString { string IConnectionString.ConnectionString => - "Host=localhost;Port=5432;Database=postgres;Username=postgres;Password=Ildan12345;"; + "Host=localhost;Port=5432;Database=OTP_sophiya;Username=postgres;Password=030405;"; } \ No newline at end of file diff --git a/StudentProgress/StudentProgress/Repositories/Implementations/GradesRepository.cs b/StudentProgress/StudentProgress/Repositories/Implementations/GradesRepository.cs index f0cacae..21958ab 100644 --- a/StudentProgress/StudentProgress/Repositories/Implementations/GradesRepository.cs +++ b/StudentProgress/StudentProgress/Repositories/Implementations/GradesRepository.cs @@ -1,11 +1,8 @@ using Dapper; using Microsoft.Extensions.Logging; using Newtonsoft.Json; +using Npgsql; using StudentProgress.Entities; -using StudentProgress.Repositories; -using System; -using System.Collections.Generic; -using System.Data.SqlClient; namespace StudentProgress.Repositories.Implementations { @@ -26,11 +23,28 @@ namespace StudentProgress.Repositories.Implementations _logger.LogDebug("Оценка: {json}", JsonConvert.SerializeObject(grade)); try { - using var connection = new SqlConnection(_connectionString.ConnectionString); - var query = @" + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + connection.Open(); + using var transaction = connection.BeginTransaction(); + var queryInsert = @" INSERT INTO Grades (SubjectsId, ProfessorsId, Date) - VALUES (@SubjectsId, @ProfessorsId, @Date)"; - connection.Execute(query, grade); + VALUES (@SubjectsId, @ProfessorsId, @Date); + SELECT MAX(Id) FROM Grades"; + var gradesId = + connection.QueryFirst(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) { @@ -45,7 +59,7 @@ namespace StudentProgress.Repositories.Implementations _logger.LogDebug("Оценка: {id}", id); try { - using var connection = new SqlConnection(_connectionString.ConnectionString); + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); var query = "DELETE FROM Grades WHERE Id = @Id"; connection.Execute(query, new { Id = id }); } @@ -61,32 +75,10 @@ namespace StudentProgress.Repositories.Implementations _logger.LogInformation("Получение оценок"); try { - using var connection = new SqlConnection(_connectionString.ConnectionString); + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); var query = "SELECT * FROM Grades"; - var parameters = new DynamicParameters(); - if (dateFrom.HasValue) - { - 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(query, parameters); + var grades = connection.Query(query); _logger.LogDebug("Полученные оценки: {json}", JsonConvert.SerializeObject(grades)); return grades; } @@ -96,25 +88,5 @@ namespace StudentProgress.Repositories.Implementations 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; - } - } } } \ No newline at end of file diff --git a/StudentProgress/StudentProgress/Repositories/Implementations/GroupRepository.cs b/StudentProgress/StudentProgress/Repositories/Implementations/GroupRepository.cs index 4c6b383..6e03080 100644 --- a/StudentProgress/StudentProgress/Repositories/Implementations/GroupRepository.cs +++ b/StudentProgress/StudentProgress/Repositories/Implementations/GroupRepository.cs @@ -25,8 +25,8 @@ public class GroupRepository : IGroupRepository try { using var connection = new NpgsqlConnection(_connectionString.ConnectionString); - var queryInsert = @"INSERT INTO Groups (NameGroup, Course, NameFaculty) -VALUES (@NameGroup, @Course, @NameFaculty)"; + var queryInsert = @"INSERT INTO ""Group"" (NameGroup) +VALUES (@NameGroup)"; connection.Execute(queryInsert, group); } catch (Exception ex) @@ -44,7 +44,7 @@ VALUES (@NameGroup, @Course, @NameFaculty)"; { using var connection = new NpgsqlConnection(_connectionString.ConnectionString); var queryDelete = @" -DELETE FROM Groups +DELETE FROM ""Group"" WHERE Id=@id"; connection.Execute(queryDelete, new { id }); } @@ -61,7 +61,7 @@ WHERE Id=@id"; try { using var connection = new NpgsqlConnection(_connectionString.ConnectionString); - var querySelect = "SELECT * FROM Groups"; + var querySelect = "SELECT * FROM \"Group\""; var groups = connection.Query(querySelect); _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(groups)); @@ -82,7 +82,7 @@ WHERE Id=@id"; { using var connection = new NpgsqlConnection(_connectionString.ConnectionString); var querySelect = @" -SELECT * FROM Groups +SELECT * FROM ""Group"" WHERE Id=@id"; var group = connection.QueryFirst(querySelect, new { @@ -109,11 +109,9 @@ WHERE Id=@id"; { using var connection = new NpgsqlConnection(_connectionString.ConnectionString); var queryUpdate = @" -UPDATE Groups +UPDATE ""Group"" SET -NameGroup=@NameGroup, -Course=@Course, -NameFaculty=@NameFaculty +NameGroup=@NameGroup WHERE Id=@Id"; connection.Execute(queryUpdate, group); } diff --git a/StudentProgress/StudentProgress/Repositories/Implementations/LecturesRepository.cs b/StudentProgress/StudentProgress/Repositories/Implementations/LecturesRepository.cs index 9208019..418a9ae 100644 --- a/StudentProgress/StudentProgress/Repositories/Implementations/LecturesRepository.cs +++ b/StudentProgress/StudentProgress/Repositories/Implementations/LecturesRepository.cs @@ -1,11 +1,8 @@ using Dapper; using Microsoft.Extensions.Logging; using Newtonsoft.Json; +using Npgsql; using StudentProgress.Entities; -using StudentProgress.Repositories; -using System; -using System.Collections.Generic; -using System.Data.SqlClient; namespace StudentProgress.Repositories.Implementations { @@ -25,7 +22,7 @@ namespace StudentProgress.Repositories.Implementations _logger.LogInformation("Получение лекций"); try { - using var connection = new SqlConnection(_connectionString.ConnectionString); + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); var query = "SELECT * FROM Lectures"; var lectures = connection.Query(query); _logger.LogDebug("Полученные лекции: {json}", JsonConvert.SerializeObject(lectures)); @@ -44,9 +41,9 @@ namespace StudentProgress.Repositories.Implementations _logger.LogDebug("Лекция: {json}", JsonConvert.SerializeObject(lecture)); try { - using var connection = new SqlConnection(_connectionString.ConnectionString); + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); var query = @" - INSERT INTO Lectures (ProfessorId, Date, Auditorium) + INSERT INTO Lectures (ProfessorsId, Date, Auditorium) VALUES (@ProfessorsId, @Date, @Auditorium)"; connection.Execute(query, lecture); } @@ -63,8 +60,8 @@ namespace StudentProgress.Repositories.Implementations _logger.LogDebug("Лекция: {id}", lectureId); try { - using var connection = new SqlConnection(_connectionString.ConnectionString); - var query = "DELETE FROM Lectures WHERE LectureId = @LectureId"; + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var query = "DELETE FROM Lectures WHERE Id = @LectureId"; connection.Execute(query, new { LectureId = lectureId }); } catch (Exception ex) diff --git a/StudentProgress/StudentProgress/Repositories/Implementations/ProfessorsNameRepository.cs b/StudentProgress/StudentProgress/Repositories/Implementations/ProfessorsRepository.cs similarity index 64% rename from StudentProgress/StudentProgress/Repositories/Implementations/ProfessorsNameRepository.cs rename to StudentProgress/StudentProgress/Repositories/Implementations/ProfessorsRepository.cs index 66a920f..24e2470 100644 --- a/StudentProgress/StudentProgress/Repositories/Implementations/ProfessorsNameRepository.cs +++ b/StudentProgress/StudentProgress/Repositories/Implementations/ProfessorsRepository.cs @@ -3,33 +3,31 @@ using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Npgsql; using StudentProgress.Entities; -using StudentProgress.Repositories; -using System.Data.SqlClient; namespace StudentProgress.Repositories.Implementations; -public class ProfessorsNameRepository : IProfessorsNameRepository +public class ProfessorsRepository : IProfessorsRepository { private readonly IConnectionString _connectionString; - private readonly ILogger _logger; + private readonly ILogger _logger; - public ProfessorsNameRepository(IConnectionString connectionString, ILogger logger) + public ProfessorsRepository(IConnectionString connectionString, ILogger logger) { _connectionString = connectionString; _logger = logger; } - public void CreateProfessorsName(Professors professorsName) + public void CreateProfessors(Professors professors) { _logger.LogInformation("Добавление объекта"); - _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(professorsName)); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(professors)); try { using var connection = new NpgsqlConnection(_connectionString.ConnectionString); - var queryInsert = @"INSERT INTO ProfessorsName (FirstName, LastName, MiddleName, Classes) -VALUES (@FirstName, @LastName, @MiddleName, @Classes)"; - connection.Execute(queryInsert, professorsName); + var queryInsert = @"INSERT INTO Professors (FirstName, Surname) + VALUES (@FirstName, @Surname)"; + connection.Execute(queryInsert, professors); } catch (Exception ex) { @@ -38,16 +36,15 @@ VALUES (@FirstName, @LastName, @MiddleName, @Classes)"; } } - public void DeleteProfessorsName(int id) + public void DeleteProfessors(int id) { _logger.LogInformation("Удаление объекта"); _logger.LogDebug("Объект: {id}", id); try { using var connection = new NpgsqlConnection(_connectionString.ConnectionString); - var queryDelete = @" -DELETE FROM ProfessorsName -WHERE Id=@id"; + var queryDelete = @"DELETE FROM Professors + WHERE Id=@id"; connection.Execute(queryDelete, new { id }); } catch (Exception ex) @@ -57,17 +54,17 @@ WHERE Id=@id"; } } - public IEnumerable ReadProfessorsName() + public IEnumerable ReadProfessors() { _logger.LogInformation("Получение всех объектов"); try { using var connection = new NpgsqlConnection(_connectionString.ConnectionString); - var querySelect = "SELECT * FROM ProfessorsName"; - var professorsNames = connection.Query(querySelect); + var querySelect = "SELECT * FROM Professors"; + var professors = connection.Query(querySelect); _logger.LogDebug("Полученные объекты: {json}", - JsonConvert.SerializeObject(professorsNames)); - return professorsNames; + JsonConvert.SerializeObject(professors)); + return professors; } catch (Exception ex) { @@ -76,7 +73,7 @@ WHERE Id=@id"; } } - public Professors ReadProfessorsNameById(int id) + public Professors ReadProfessorsById(int id) { _logger.LogInformation("Получение объекта по идентификатору"); _logger.LogDebug("Объект: {id}", id); @@ -84,13 +81,13 @@ WHERE Id=@id"; { using var connection = new NpgsqlConnection(_connectionString.ConnectionString); var querySelect = @" -SELECT * FROM ProfessorsName -WHERE Id=@id"; - var professorsName = connection.QueryFirst(querySelect, new { id }); + SELECT * FROM Professors + WHERE Id=@id"; + var professors = connection.QueryFirst(querySelect, new { id }); _logger.LogDebug("Найденный объект: {json}", - JsonConvert.SerializeObject(professorsName)); - return professorsName; + JsonConvert.SerializeObject(professors)); + return professors; } catch (Exception ex) { @@ -99,7 +96,7 @@ WHERE Id=@id"; } } - public void UpdateProfessorsName(Professors professorsName) + public void UpdateProfessors(Professors professorsName) { _logger.LogInformation("Редактирование объекта"); _logger.LogDebug("Объект: {json}", @@ -108,13 +105,11 @@ WHERE Id=@id"; { using var connection = new NpgsqlConnection(_connectionString.ConnectionString); var queryUpdate = @" - UPDATE ProfessorsName -SET -FirstName=@FirstName, -LastName=@LastName, -MiddleName=@MiddleName, -Classes=@Classes -WHERE Id=@Id"; + UPDATE Professors + SET + FirstName=@FirstName, + Surname=@Surname + WHERE Id=@Id"; connection.Execute(queryUpdate, professorsName); } catch (Exception ex) diff --git a/StudentProgress/StudentProgress/Repositories/Implementations/StudentRepository.cs b/StudentProgress/StudentProgress/Repositories/Implementations/StudentRepository.cs index a0bb006..f5baf2b 100644 --- a/StudentProgress/StudentProgress/Repositories/Implementations/StudentRepository.cs +++ b/StudentProgress/StudentProgress/Repositories/Implementations/StudentRepository.cs @@ -28,8 +28,8 @@ public class StudentRepository : IStudentRepository { using var connection = new NpgsqlConnection(_connectionString.ConnectionString); var queryInsert = @" -INSERT INTO Student (FirstName, LastName, MiddleName, Phone, GroupID) -VALUES (@FirstName, @LastName, @MiddleName, @Phone, @GroupID)"; +INSERT INTO Student (Name, Surname, GroupId) +VALUES (@Name, @Surname, @GroupId)"; connection.Execute(queryInsert, student); } catch (Exception ex) @@ -113,11 +113,9 @@ WHERE Id=@id"; var queryUpdate = @" UPDATE Student SET -FirstName=@FirstName, -LastName=@LastName, -MiddleName=@MiddleName, -Phone=@Phone, -GroupID=@GroupID +Name=@Name, +Surname=@Surname, +GroupId=@GroupId WHERE Id=@Id"; connection.Execute(queryUpdate, student); } diff --git a/StudentProgress/StudentProgress/Repositories/Implementations/SubjectsRepository.cs b/StudentProgress/StudentProgress/Repositories/Implementations/SubjectsRepository.cs index 5f77047..9465931 100644 --- a/StudentProgress/StudentProgress/Repositories/Implementations/SubjectsRepository.cs +++ b/StudentProgress/StudentProgress/Repositories/Implementations/SubjectsRepository.cs @@ -17,28 +17,17 @@ namespace StudentProgress.Repositories.Implementations _logger = logger; } - // Добавление нового предмета public void CreateSubjects_(Subjects subject) { _logger.LogInformation("Добавление объекта"); _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(subject)); + try { using var connection = new NpgsqlConnection(_connectionString.ConnectionString); - connection.Open(); - using var transaction = connection.BeginTransaction(); - - var queryInsert = @" -INSERT INTO Subject (NameSubject) -VALUES (@NameSubject); -SELECT MAX(Id) FROM Subject"; - - // Выполняем запрос и получаем ID созданного предмета - var subjectId = connection.QueryFirst(queryInsert, subject, transaction); - - transaction.Commit(); - - _logger.LogInformation("Успешно добавлен объект с Id: {id}", subjectId); + var queryInsert = @"INSERT INTO Subjects (NameSubject, Course) + VALUES (@NameSubject, @Course)"; + connection.Execute(queryInsert, subject); } catch (Exception ex) { @@ -47,7 +36,6 @@ SELECT MAX(Id) FROM Subject"; } } - // Удаление предмета по идентификатору public void DeleteSubjects(int id) { _logger.LogInformation("Удаление объекта"); @@ -55,20 +43,9 @@ SELECT MAX(Id) FROM Subject"; try { using var connection = new NpgsqlConnection(_connectionString.ConnectionString); - var queryDelete = @" -DELETE FROM Subject -WHERE Id=@Id"; - - var rowsAffected = connection.Execute(queryDelete, new { Id = id }); - - if (rowsAffected == 0) - { - _logger.LogWarning("Объект с Id: {id} не найден для удаления", id); - } - else - { - _logger.LogInformation("Объект с Id: {id} успешно удалён", id); - } + var queryDelete = @"DELETE FROM Subjects + WHERE Id=@id"; + connection.Execute(queryDelete, new { id }); } catch (Exception ex) { @@ -77,44 +54,17 @@ WHERE Id=@Id"; } } - // Получение всех предметов public IEnumerable ReadSubjects(int? id = null) { - _logger.LogInformation("Получение объектов"); + _logger.LogInformation("Получение всех объектов"); try { using var connection = new NpgsqlConnection(_connectionString.ConnectionString); - - if (id.HasValue) - { - // Если указан ID, возвращаем конкретный предмет - var querySelectById = @" -SELECT * FROM Subject -WHERE Id = @Id"; - - var subject = connection.Query(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(querySelectAll).ToList(); - _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(subjects)); - - return subjects; - } + var querySelect = "SELECT * FROM Subjects"; + var subjects = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты: {json}", + JsonConvert.SerializeObject(subjects)); + return subjects; } catch (Exception ex) { @@ -123,7 +73,6 @@ WHERE Id = @Id"; } } - // Получение предмета по идентификатору public Subjects ReadSubjectById(int id) { _logger.LogInformation("Получение объекта по идентификатору"); @@ -131,21 +80,11 @@ WHERE Id = @Id"; try { using var connection = new NpgsqlConnection(_connectionString.ConnectionString); - var querySelect = @" -SELECT * FROM Subject -WHERE Id = @Id"; - - var subject = connection.QueryFirstOrDefault(querySelect, new { Id = id }); - - if (subject == null) - { - _logger.LogWarning("Объект с Id: {id} не найден", id); - } - else - { - _logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(subject)); - } - + var querySelect = @"SELECT * FROM Subjects + WHERE Id=@id"; + var subject = connection.QueryFirst(querySelect, new { id }); + _logger.LogDebug("Найденный объект: {json}", + JsonConvert.SerializeObject(subject)); return subject; } catch (Exception ex) @@ -155,7 +94,6 @@ WHERE Id = @Id"; } } - // Обновление данных предмета public void UpdateSubject(Subjects subject) { _logger.LogInformation("Редактирование объекта"); @@ -166,11 +104,11 @@ WHERE Id = @Id"; connection.Open(); using var transaction = connection.BeginTransaction(); - var queryUpdate = @" -UPDATE Subject -SET NameSubject = @NameSubject -WHERE Id = @Id"; - + var queryUpdate = @"UPDATE Subjects + SET + NameSubject = @NameSubject, + Course = @Course + WHERE Id = @Id"; connection.Execute(queryUpdate, subject, transaction); transaction.Commit();