ИСЭбд-22. Мухамадиева С.С. Лабораторная работа №2 #2

Closed
safia wants to merge 7 commits from LabWork_2 into LabWork_1
17 changed files with 119 additions and 251 deletions
Showing only changes of commit fdb6376672 - Show all commits

View File

@ -18,16 +18,4 @@ public class Grades
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 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));

View File

@ -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;

View File

@ -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));

View File

@ -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));

View File

@ -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;

View File

@ -42,7 +42,7 @@ namespace StudentProgress
container.RegisterType<IGradesRepository, GradesRepository>(new TransientLifetimeManager());
container.RegisterType<IGroupRepository, GroupRepository>(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<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
{
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 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<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)
{
@ -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<Grades>(query, parameters);
var grades = connection.Query<Grades>(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;
}
}
}
}

View File

@ -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<Group>(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<Group>(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);
}

View File

@ -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<Lectures>(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)

View File

@ -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<ProfessorsNameRepository> _logger;
private readonly ILogger<ProfessorsRepository> _logger;
public ProfessorsNameRepository(IConnectionString connectionString, ILogger<ProfessorsNameRepository> logger)
public ProfessorsRepository(IConnectionString connectionString, ILogger<ProfessorsRepository> 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<Professors> ReadProfessorsName()
public IEnumerable<Professors> ReadProfessors()
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM ProfessorsName";
var professorsNames = connection.Query<Professors>(querySelect);
var querySelect = "SELECT * FROM Professors";
var professors = connection.Query<Professors>(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<Professors>(querySelect, new { id });
SELECT * FROM Professors
WHERE Id=@id";
var professors = connection.QueryFirst<Professors>(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)

View File

@ -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);
}

View File

@ -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<int>(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<Subjects> 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<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;
}
var querySelect = "SELECT * FROM Subjects";
var subjects = connection.Query<Subjects>(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<Subjects>(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<Subjects>(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();