fix in course models, logic and storage, add last forms

This commit is contained in:
DavidMakarov 2024-05-07 23:34:50 +04:00
parent d60d364d16
commit 6aca477044
19 changed files with 279 additions and 128 deletions

View File

@ -43,7 +43,7 @@ namespace StudentEnrollmentBusinessLogic
_logger.LogWarning("ReadElement element not found"); _logger.LogWarning("ReadElement element not found");
return null; return null;
} }
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id); _logger.LogInformation("ReadElement find. Id:{Id}", element.course_id);
return element; return element;
} }
public bool Create(CourseBindingModel model) public bool Create(CourseBindingModel model)
@ -69,7 +69,7 @@ namespace StudentEnrollmentBusinessLogic
public bool Delete(CourseBindingModel model) public bool Delete(CourseBindingModel model)
{ {
CheckModel(model, false); CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id); _logger.LogInformation("Delete. Id:{Id}", model.course_id);
if (_courseStorage.Delete(model) == null) if (_courseStorage.Delete(model) == null)
{ {
_logger.LogWarning("Delete operation failed"); _logger.LogWarning("Delete operation failed");
@ -87,17 +87,17 @@ namespace StudentEnrollmentBusinessLogic
{ {
return; return;
} }
if (string.IsNullOrEmpty(model.CourseName)) if (string.IsNullOrEmpty(model.name))
{ {
throw new ArgumentNullException("Нет названия направления!", throw new ArgumentNullException("Нет названия направления!",
nameof(model.CourseName)); nameof(model.name));
} }
_logger.LogInformation("Course. CourseName:{CourseName}. Id: { Id}", model.CourseName, model.Id); _logger.LogInformation("Course. CourseName:{CourseName}. Id: { Id}", model.name, model.course_id);
var element = _courseStorage.GetElement(new CourseSearchModel var element = _courseStorage.GetElement(new CourseSearchModel
{ {
name = model.CourseName name = model.name
}); });
if (element != null && element.Id != model.Id) if (element != null && element.course_id != model.course_id)
{ {
throw new InvalidOperationException("Направление с таким названием уже есть"); throw new InvalidOperationException("Направление с таким названием уже есть");
} }

View File

@ -4,8 +4,8 @@ namespace StudentEnrollmentContracts.BindingModels
{ {
public class CourseBindingModel : ICourseModel public class CourseBindingModel : ICourseModel
{ {
public int Id { get; set; } public int course_id { get; set; }
public string CourseName { get; set; } = string.Empty; public string name { get; set; } = string.Empty;
public int FacultyId { get; set; } public int facultyid { get; set; }
} }
} }

View File

@ -5,11 +5,11 @@ namespace StudentEnrollmentContracts.ViewModels
{ {
public class CourseViewModel : ICourseModel public class CourseViewModel : ICourseModel
{ {
public int Id { get; set; } public int course_id { get; set; }
[DisplayName("Название направления")] [DisplayName("Название направления")]
public string CourseName { get; set; } = string.Empty; public string name { get; set; } = string.Empty;
[DisplayName("Название факультета")] [DisplayName("Название факультета")]
public string FacultyName { get; set; } = string.Empty; public string FacultyName { get; set; } = string.Empty;
public int FacultyId { get; set; } public int facultyid { get; set; }
} }
} }

View File

@ -18,7 +18,7 @@ namespace StudentEnrollmentContracts.ViewModels
public long TIN { get; set; } public long TIN { get; set; }
public int ExamPointsId { get; set; } public int ExamPointsId { get; set; }
[DisplayName("Суммарное количество баллов")] [DisplayName("Суммарное количество баллов")]
public int ExamPoints { get; set; } public int Summary { get; set; }
public Dictionary<int, ICourseModel> StudentCourse public Dictionary<int, ICourseModel> StudentCourse
{ {
get; get;

View File

@ -1,8 +1,9 @@
namespace StudentEnrollmentDataModels.Models namespace StudentEnrollmentDataModels.Models
{ {
public interface ICourseModel : IId public interface ICourseModel //: IId
{ {
string CourseName { get; } int course_id { get; }
int FacultyId { get; } string name { get; }
int facultyid { get; }
} }
} }

View File

@ -60,7 +60,7 @@ namespace StudentEnrollmentDatabaseImplement.Implements
public CourseViewModel? Update(CourseBindingModel model) public CourseViewModel? Update(CourseBindingModel model)
{ {
using var context = new StudentEnrollmentDatabase(); using var context = new StudentEnrollmentDatabase();
var course = context.course.Include(x => x.Faculty).FirstOrDefault(x => x.course_id == model.Id); var course = context.course.Include(x => x.Faculty).FirstOrDefault(x => x.course_id == model.course_id);
if (course == null) if (course == null)
{ {
return null; return null;
@ -72,7 +72,7 @@ namespace StudentEnrollmentDatabaseImplement.Implements
public CourseViewModel? Delete(CourseBindingModel model) public CourseViewModel? Delete(CourseBindingModel model)
{ {
using var context = new StudentEnrollmentDatabase(); using var context = new StudentEnrollmentDatabase();
var element = context.course.Include(x => x.Faculty).FirstOrDefault(rec => rec.course_id == model.Id); var element = context.course.Include(x => x.Faculty).FirstOrDefault(rec => rec.course_id == model.course_id);
if (element != null) if (element != null)
{ {
context.course.Remove(element); context.course.Remove(element);

View File

@ -14,6 +14,8 @@ namespace StudentEnrollmentDatabaseImplement.Implements
using var context = new StudentEnrollmentDatabase(); using var context = new StudentEnrollmentDatabase();
return context.student return context.student
.Include(x => x.ExamPoints) .Include(x => x.ExamPoints)
.Include(x => x.Courses)
.ThenInclude(x => x.Course)
.Select(x => x.GetViewModel) .Select(x => x.GetViewModel)
.ToList(); .ToList();
} }
@ -26,7 +28,9 @@ namespace StudentEnrollmentDatabaseImplement.Implements
using var context = new StudentEnrollmentDatabase(); using var context = new StudentEnrollmentDatabase();
return context.student return context.student
.Include(x => x.ExamPoints) .Include(x => x.ExamPoints)
.Where(x => (model.student_id.HasValue && x.student_id == model.student_id) || (model.tin == 0 && x.tin == model.tin)) .Include(x => x.Courses)
.ThenInclude(x => x.Course)
.Where(x => (model.student_id.HasValue && x.student_id == model.student_id) || (model.tin == 0 && x.tin == model.tin))
.Select(x => x.GetViewModel) .Select(x => x.GetViewModel)
.ToList(); .ToList();
} }
@ -39,7 +43,9 @@ namespace StudentEnrollmentDatabaseImplement.Implements
using var context = new StudentEnrollmentDatabase(); using var context = new StudentEnrollmentDatabase();
return context.student return context.student
.Include(x => x.ExamPoints) .Include(x => x.ExamPoints)
.FirstOrDefault(x => (model.student_id.HasValue && x.student_id == model.student_id) || (model.tin == 0 && x.tin == model.tin))? .Include(x => x.Courses)
.ThenInclude(x => x.Course)
.FirstOrDefault(x => (model.student_id.HasValue && x.student_id == model.student_id) || (model.tin == 0 && x.tin == model.tin))?
.GetViewModel; .GetViewModel;
} }
public StudentViewModel? Insert(StudentBindingModel model) public StudentViewModel? Insert(StudentBindingModel model)
@ -52,24 +58,48 @@ namespace StudentEnrollmentDatabaseImplement.Implements
} }
context.student.Add(newStudent); context.student.Add(newStudent);
context.SaveChanges(); context.SaveChanges();
return context.student.Include(x => x.ExamPoints).FirstOrDefault(x => x.student_id == newStudent.student_id)?.GetViewModel; return context.student
.Include(x => x.ExamPoints)
.Include(x => x.Courses)
.ThenInclude(x => x.Course)
.FirstOrDefault(x => x.student_id == newStudent.student_id)?.GetViewModel;
} }
public StudentViewModel? Update(StudentBindingModel model) public StudentViewModel? Update(StudentBindingModel model)
{ {
using var context = new StudentEnrollmentDatabase(); using var context = new StudentEnrollmentDatabase();
var student = context.student.FirstOrDefault(x => x.student_id == model.Id); using var transaction = context.Database.BeginTransaction();
if (student == null) try
{ {
return null; var student = context.student
.Include(x => x.ExamPoints)
.Include(x => x.Courses)
.ThenInclude(x => x.Course)
.FirstOrDefault(x => x.student_id == model.Id);
if (student == null)
{
return null;
}
student.Update(model);
context.SaveChanges();
student.UpdateCourses(context, model);
context.SaveChanges();
transaction.Commit();
return student.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
} }
student.Update(model);
context.SaveChanges();
return student.GetViewModel;
} }
public StudentViewModel? Delete(StudentBindingModel model) public StudentViewModel? Delete(StudentBindingModel model)
{ {
using var context = new StudentEnrollmentDatabase(); using var context = new StudentEnrollmentDatabase();
var element = context.student.FirstOrDefault(rec => rec.student_id == model.Id); var element = context.student
.Include(x => x.ExamPoints)
.Include(x => x.Courses)
.ThenInclude(x => x.Course)
.FirstOrDefault(rec => rec.student_id == model.Id);
if (element != null) if (element != null)
{ {
context.student.Remove(element); context.student.Remove(element);

View File

@ -11,7 +11,7 @@ using StudentEnrollmentDatabaseImplement;
namespace StudentEnrollmentDatabaseImplement.Migrations namespace StudentEnrollmentDatabaseImplement.Migrations
{ {
[DbContext(typeof(StudentEnrollmentDatabase))] [DbContext(typeof(StudentEnrollmentDatabase))]
[Migration("20240506162134_InitCreate")] [Migration("20240507161008_InitCreate")]
partial class InitCreate partial class InitCreate
{ {
/// <inheritdoc /> /// <inheritdoc />
@ -136,23 +136,23 @@ namespace StudentEnrollmentDatabaseImplement.Migrations
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("student_course_id")); NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("student_course_id"));
b.Property<int>("CourseId") b.Property<int>("course_id")
.HasColumnType("integer");
b.Property<int>("StudentId")
.HasColumnType("integer"); .HasColumnType("integer");
b.Property<int>("courseid") b.Property<int>("courseid")
.HasColumnType("integer"); .HasColumnType("integer");
b.Property<int>("student_id")
.HasColumnType("integer");
b.Property<int>("studentid") b.Property<int>("studentid")
.HasColumnType("integer"); .HasColumnType("integer");
b.HasKey("student_course_id"); b.HasKey("student_course_id");
b.HasIndex("CourseId"); b.HasIndex("course_id");
b.HasIndex("StudentId"); b.HasIndex("student_id");
b.ToTable("student_course"); b.ToTable("student_course");
}); });
@ -182,14 +182,14 @@ namespace StudentEnrollmentDatabaseImplement.Migrations
modelBuilder.Entity("StudentEnrollmentDatabaseImplement.Models.StudentCourse", b => modelBuilder.Entity("StudentEnrollmentDatabaseImplement.Models.StudentCourse", b =>
{ {
b.HasOne("StudentEnrollmentDatabaseImplement.Models.Course", "Course") b.HasOne("StudentEnrollmentDatabaseImplement.Models.Course", "Course")
.WithMany("StudentCourses") .WithMany("student_course")
.HasForeignKey("CourseId") .HasForeignKey("course_id")
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
.IsRequired(); .IsRequired();
b.HasOne("StudentEnrollmentDatabaseImplement.Models.Student", "Student") b.HasOne("StudentEnrollmentDatabaseImplement.Models.Student", "Student")
.WithMany("Courses") .WithMany("Courses")
.HasForeignKey("StudentId") .HasForeignKey("student_id")
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
.IsRequired(); .IsRequired();
@ -200,7 +200,7 @@ namespace StudentEnrollmentDatabaseImplement.Migrations
modelBuilder.Entity("StudentEnrollmentDatabaseImplement.Models.Course", b => modelBuilder.Entity("StudentEnrollmentDatabaseImplement.Models.Course", b =>
{ {
b.Navigation("StudentCourses"); b.Navigation("student_course");
}); });
modelBuilder.Entity("StudentEnrollmentDatabaseImplement.Models.Student", b => modelBuilder.Entity("StudentEnrollmentDatabaseImplement.Models.Student", b =>

View File

@ -93,21 +93,21 @@ namespace StudentEnrollmentDatabaseImplement.Migrations
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
studentid = table.Column<int>(type: "integer", nullable: false), studentid = table.Column<int>(type: "integer", nullable: false),
courseid = table.Column<int>(type: "integer", nullable: false), courseid = table.Column<int>(type: "integer", nullable: false),
StudentId = table.Column<int>(type: "integer", nullable: false), student_id = table.Column<int>(type: "integer", nullable: false),
CourseId = table.Column<int>(type: "integer", nullable: false) course_id = table.Column<int>(type: "integer", nullable: false)
}, },
constraints: table => constraints: table =>
{ {
table.PrimaryKey("PK_student_course", x => x.student_course_id); table.PrimaryKey("PK_student_course", x => x.student_course_id);
table.ForeignKey( table.ForeignKey(
name: "FK_student_course_course_CourseId", name: "FK_student_course_course_course_id",
column: x => x.CourseId, column: x => x.course_id,
principalTable: "course", principalTable: "course",
principalColumn: "course_id", principalColumn: "course_id",
onDelete: ReferentialAction.Cascade); onDelete: ReferentialAction.Cascade);
table.ForeignKey( table.ForeignKey(
name: "FK_student_course_student_StudentId", name: "FK_student_course_student_student_id",
column: x => x.StudentId, column: x => x.student_id,
principalTable: "student", principalTable: "student",
principalColumn: "student_id", principalColumn: "student_id",
onDelete: ReferentialAction.Cascade); onDelete: ReferentialAction.Cascade);
@ -124,14 +124,14 @@ namespace StudentEnrollmentDatabaseImplement.Migrations
column: "exampointsid"); column: "exampointsid");
migrationBuilder.CreateIndex( migrationBuilder.CreateIndex(
name: "IX_student_course_CourseId", name: "IX_student_course_course_id",
table: "student_course", table: "student_course",
column: "CourseId"); column: "course_id");
migrationBuilder.CreateIndex( migrationBuilder.CreateIndex(
name: "IX_student_course_StudentId", name: "IX_student_course_student_id",
table: "student_course", table: "student_course",
column: "StudentId"); column: "student_id");
} }
/// <inheritdoc /> /// <inheritdoc />

View File

@ -133,23 +133,23 @@ namespace StudentEnrollmentDatabaseImplement.Migrations
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("student_course_id")); NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("student_course_id"));
b.Property<int>("CourseId") b.Property<int>("course_id")
.HasColumnType("integer");
b.Property<int>("StudentId")
.HasColumnType("integer"); .HasColumnType("integer");
b.Property<int>("courseid") b.Property<int>("courseid")
.HasColumnType("integer"); .HasColumnType("integer");
b.Property<int>("student_id")
.HasColumnType("integer");
b.Property<int>("studentid") b.Property<int>("studentid")
.HasColumnType("integer"); .HasColumnType("integer");
b.HasKey("student_course_id"); b.HasKey("student_course_id");
b.HasIndex("CourseId"); b.HasIndex("course_id");
b.HasIndex("StudentId"); b.HasIndex("student_id");
b.ToTable("student_course"); b.ToTable("student_course");
}); });
@ -179,14 +179,14 @@ namespace StudentEnrollmentDatabaseImplement.Migrations
modelBuilder.Entity("StudentEnrollmentDatabaseImplement.Models.StudentCourse", b => modelBuilder.Entity("StudentEnrollmentDatabaseImplement.Models.StudentCourse", b =>
{ {
b.HasOne("StudentEnrollmentDatabaseImplement.Models.Course", "Course") b.HasOne("StudentEnrollmentDatabaseImplement.Models.Course", "Course")
.WithMany("StudentCourses") .WithMany("student_course")
.HasForeignKey("CourseId") .HasForeignKey("course_id")
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
.IsRequired(); .IsRequired();
b.HasOne("StudentEnrollmentDatabaseImplement.Models.Student", "Student") b.HasOne("StudentEnrollmentDatabaseImplement.Models.Student", "Student")
.WithMany("Courses") .WithMany("Courses")
.HasForeignKey("StudentId") .HasForeignKey("student_id")
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
.IsRequired(); .IsRequired();
@ -197,7 +197,7 @@ namespace StudentEnrollmentDatabaseImplement.Migrations
modelBuilder.Entity("StudentEnrollmentDatabaseImplement.Models.Course", b => modelBuilder.Entity("StudentEnrollmentDatabaseImplement.Models.Course", b =>
{ {
b.Navigation("StudentCourses"); b.Navigation("student_course");
}); });
modelBuilder.Entity("StudentEnrollmentDatabaseImplement.Models.Student", b => modelBuilder.Entity("StudentEnrollmentDatabaseImplement.Models.Student", b =>

View File

@ -6,16 +6,16 @@ using System.ComponentModel.DataAnnotations.Schema;
namespace StudentEnrollmentDatabaseImplement.Models namespace StudentEnrollmentDatabaseImplement.Models
{ {
public class Course // : ICourseModel public class Course : ICourseModel
{ {
[Key] [Key]
public int course_id { get; private set; } public int course_id { get; private set; }
[Required] [Required]
public string name { get; private set; } = string.Empty; public string name { get; private set; } = string.Empty;
[Required] [Required]
public int facultyid { get; private set; } public int facultyid { get; set; }
public virtual Faculty Faculty { get; set; } public virtual Faculty Faculty { get; set; }
[ForeignKey("CourseId")] [ForeignKey("courseid")]
public virtual List<StudentCourse> StudentCourses { get; set; } = new(); public virtual List<StudentCourse> StudentCourses { get; set; } = new();
public static Course? Create(CourseBindingModel model) public static Course? Create(CourseBindingModel model)
{ {
@ -25,9 +25,9 @@ namespace StudentEnrollmentDatabaseImplement.Models
} }
return new Course() return new Course()
{ {
course_id = model.Id, course_id = model.course_id,
name = model.CourseName, name = model.name,
facultyid = model.FacultyId, facultyid = model.facultyid,
}; };
} }
public void Update(CourseBindingModel model) public void Update(CourseBindingModel model)
@ -36,14 +36,14 @@ namespace StudentEnrollmentDatabaseImplement.Models
{ {
return; return;
} }
name = model.CourseName; name = model.name;
facultyid = model.FacultyId; facultyid = model.facultyid;
} }
public CourseViewModel GetViewModel => new() public CourseViewModel GetViewModel => new()
{ {
Id = course_id, course_id = course_id,
CourseName = name, name = name,
FacultyId = facultyid, facultyid = facultyid,
FacultyName = Faculty.name, FacultyName = Faculty.name,
}; };
} }

View File

@ -22,20 +22,21 @@ namespace StudentEnrollmentDatabaseImplement.Models
[Required] [Required]
public int exampointsid { get; private set; } public int exampointsid { get; private set; }
public virtual ExamPoints ExamPoints { get; private set; } public virtual ExamPoints ExamPoints { get; private set; }
private Dictionary<int, ICourseModel>? _StudentCourse = null; private Dictionary<int, ICourseModel>? _studentCourse = null;
[NotMapped]
public Dictionary<int, ICourseModel> StudentCourse public Dictionary<int, ICourseModel> StudentCourse
{ {
get get
{ {
if (_StudentCourse == null) if (_studentCourse == null)
{ {
_StudentCourse = Courses.ToDictionary(SC => SC.courseid, _studentCourse = Courses
SC => SC.Course as ICourseModel); .ToDictionary(x => x.courseid, x => x.Course as ICourseModel);
} }
return _StudentCourse; return _studentCourse;
} }
} }
[ForeignKey("StudentId")] [ForeignKey("studentid")]
public virtual List<StudentCourse> Courses { get; set; } = new(); public virtual List<StudentCourse> Courses { get; set; } = new();
public static Student? Create(StudentEnrollmentDatabase context,StudentBindingModel model) public static Student? Create(StudentEnrollmentDatabase context,StudentBindingModel model)
{ {
@ -80,7 +81,35 @@ namespace StudentEnrollmentDatabaseImplement.Models
TIN = tin, TIN = tin,
Email = email, Email = email,
ExamPointsId = exampointsid, ExamPointsId = exampointsid,
ExamPoints = ExamPoints.summary, Summary = ExamPoints.summary,
StudentCourse = StudentCourse,
}; };
public void UpdateCourses(StudentEnrollmentDatabase context, StudentBindingModel model)
{
var StudentCourses = context.student_course.Where(rec => rec.studentid == model.Id).ToList();
if (StudentCourses != null)
{
context.student_course.RemoveRange(StudentCourses.Where(rec
=> !model.StudentCourse.ContainsKey(rec.courseid)));
context.SaveChanges();
foreach (var updateCourse in StudentCourses)
{
model.StudentCourse.Remove(updateCourse.courseid);
}
context.SaveChanges();
}
var Student = context.student.First(x => x.student_id == student_id);
foreach (var pc in model.StudentCourse)
{
context.student_course.Add(new StudentCourse
{
Student = Student,
Course = context.course.First(x => x.course_id == pc.Key),
});
context.SaveChanges();
}
_studentCourse = null;
}
} }
} }

View File

@ -56,9 +56,9 @@ namespace StudentEnrollmentView
{ {
var operationResult = _logicC.Create(new CourseBindingModel var operationResult = _logicC.Create(new CourseBindingModel
{ {
Id = _id ?? 0, course_id = _id ?? 0,
CourseName = textBoxName.Text, name = textBoxName.Text,
FacultyId = Convert.ToInt32(comboBoxFaculty.SelectedValue) facultyid = Convert.ToInt32(comboBoxFaculty.SelectedValue)
}); });
if (!operationResult) if (!operationResult)
{ {

View File

@ -77,7 +77,7 @@ namespace StudentEnrollmentView
{ {
if (!_logic.Delete(new CourseBindingModel if (!_logic.Delete(new CourseBindingModel
{ {
Id = id course_id = id
})) }))
{ {
throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");

View File

@ -43,77 +43,72 @@
// label2 // label2
// //
label2.AutoSize = true; label2.AutoSize = true;
label2.Location = new Point(12, 31); label2.Location = new Point(10, 23);
label2.Name = "label2"; label2.Name = "label2";
label2.Size = new Size(129, 20); label2.Size = new Size(102, 15);
label2.TabIndex = 7; label2.TabIndex = 7;
label2.Text = "Первый экзамен:"; label2.Text = "Первый экзамен:";
// //
// textBoxFirstExamPoints // textBoxFirstExamPoints
// //
textBoxFirstExamPoints.Location = new Point(180, 28); textBoxFirstExamPoints.Location = new Point(158, 21);
textBoxFirstExamPoints.Margin = new Padding(3, 4, 3, 4);
textBoxFirstExamPoints.Name = "textBoxFirstExamPoints"; textBoxFirstExamPoints.Name = "textBoxFirstExamPoints";
textBoxFirstExamPoints.Size = new Size(285, 27); textBoxFirstExamPoints.Size = new Size(250, 23);
textBoxFirstExamPoints.TabIndex = 6; textBoxFirstExamPoints.TabIndex = 6;
// //
// label1 // label1
// //
label1.AutoSize = true; label1.AutoSize = true;
label1.Location = new Point(12, 79); label1.Location = new Point(10, 59);
label1.Name = "label1"; label1.Name = "label1";
label1.Size = new Size(124, 20); label1.Size = new Size(98, 15);
label1.TabIndex = 9; label1.TabIndex = 9;
label1.Text = "Второй экзамен:"; label1.Text = "Второй экзамен:";
// //
// textBoxSecondExamPoints // textBoxSecondExamPoints
// //
textBoxSecondExamPoints.Location = new Point(180, 76); textBoxSecondExamPoints.Location = new Point(158, 57);
textBoxSecondExamPoints.Margin = new Padding(3, 4, 3, 4);
textBoxSecondExamPoints.Name = "textBoxSecondExamPoints"; textBoxSecondExamPoints.Name = "textBoxSecondExamPoints";
textBoxSecondExamPoints.Size = new Size(285, 27); textBoxSecondExamPoints.Size = new Size(250, 23);
textBoxSecondExamPoints.TabIndex = 8; textBoxSecondExamPoints.TabIndex = 8;
// //
// label3 // label3
// //
label3.AutoSize = true; label3.AutoSize = true;
label3.Location = new Point(12, 131); label3.Location = new Point(10, 98);
label3.Name = "label3"; label3.Name = "label3";
label3.Size = new Size(122, 20); label3.Size = new Size(96, 15);
label3.TabIndex = 11; label3.TabIndex = 11;
label3.Text = "Третий экзамен:"; label3.Text = "Третий экзамен:";
// //
// textBoxThirdExamPoints // textBoxThirdExamPoints
// //
textBoxThirdExamPoints.Location = new Point(180, 128); textBoxThirdExamPoints.Location = new Point(158, 96);
textBoxThirdExamPoints.Margin = new Padding(3, 4, 3, 4);
textBoxThirdExamPoints.Name = "textBoxThirdExamPoints"; textBoxThirdExamPoints.Name = "textBoxThirdExamPoints";
textBoxThirdExamPoints.Size = new Size(285, 27); textBoxThirdExamPoints.Size = new Size(250, 23);
textBoxThirdExamPoints.TabIndex = 10; textBoxThirdExamPoints.TabIndex = 10;
// //
// label4 // label4
// //
label4.AutoSize = true; label4.AutoSize = true;
label4.Location = new Point(12, 183); label4.Location = new Point(10, 137);
label4.Name = "label4"; label4.Name = "label4";
label4.Size = new Size(91, 20); label4.Size = new Size(74, 15);
label4.TabIndex = 13; label4.TabIndex = 13;
label4.Text = "Доп. баллы:"; label4.Text = "Доп. баллы:";
// //
// textBoxAddPoints // textBoxAddPoints
// //
textBoxAddPoints.Location = new Point(180, 180); textBoxAddPoints.Location = new Point(158, 135);
textBoxAddPoints.Margin = new Padding(3, 4, 3, 4);
textBoxAddPoints.Name = "textBoxAddPoints"; textBoxAddPoints.Name = "textBoxAddPoints";
textBoxAddPoints.Size = new Size(285, 27); textBoxAddPoints.Size = new Size(250, 23);
textBoxAddPoints.TabIndex = 12; textBoxAddPoints.TabIndex = 12;
// //
// buttonCancel // buttonCancel
// //
buttonCancel.Location = new Point(352, 258); buttonCancel.Location = new Point(308, 194);
buttonCancel.Margin = new Padding(3, 4, 3, 4);
buttonCancel.Name = "buttonCancel"; buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(119, 37); buttonCancel.Size = new Size(104, 28);
buttonCancel.TabIndex = 15; buttonCancel.TabIndex = 15;
buttonCancel.Text = "Отмена"; buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true; buttonCancel.UseVisualStyleBackColor = true;
@ -121,10 +116,9 @@
// //
// buttonSave // buttonSave
// //
buttonSave.Location = new Point(226, 258); buttonSave.Location = new Point(198, 194);
buttonSave.Margin = new Padding(3, 4, 3, 4);
buttonSave.Name = "buttonSave"; buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(119, 37); buttonSave.Size = new Size(104, 28);
buttonSave.TabIndex = 14; buttonSave.TabIndex = 14;
buttonSave.Text = "Сохранить"; buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true; buttonSave.UseVisualStyleBackColor = true;
@ -132,9 +126,9 @@
// //
// FormExamPoints // FormExamPoints
// //
AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(494, 308); ClientSize = new Size(432, 231);
Controls.Add(buttonCancel); Controls.Add(buttonCancel);
Controls.Add(buttonSave); Controls.Add(buttonSave);
Controls.Add(label4); Controls.Add(label4);
@ -145,8 +139,10 @@
Controls.Add(textBoxSecondExamPoints); Controls.Add(textBoxSecondExamPoints);
Controls.Add(label2); Controls.Add(label2);
Controls.Add(textBoxFirstExamPoints); Controls.Add(textBoxFirstExamPoints);
Margin = new Padding(3, 2, 3, 2);
Name = "FormExamPoints"; Name = "FormExamPoints";
Text = "Баллы за экзамены"; Text = "Баллы за экзамены";
Load += FormExamPoints_Load;
ResumeLayout(false); ResumeLayout(false);
PerformLayout(); PerformLayout();
} }

View File

@ -1,6 +1,9 @@
using StudentEnrollmentContracts.BindingModels; using StudentEnrollmentContracts.BindingModels;
using StudentEnrollmentContracts.BusinessLogicContracts; using StudentEnrollmentContracts.BusinessLogicContracts;
using StudentEnrollmentContracts.SearchModels;
using StudentEnrollmentDatabaseImplement.Models;
using StudentEnrollmentDataModels.Models; using StudentEnrollmentDataModels.Models;
using System.Windows.Forms;
namespace StudentEnrollmentView namespace StudentEnrollmentView
{ {
@ -27,6 +30,11 @@ namespace StudentEnrollmentView
MessageBox.Show("Заполните баллы за второй экзамен", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Заполните баллы за второй экзамен", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return; return;
} }
if (string.IsNullOrEmpty(textBoxThirdExamPoints.Text))
{
MessageBox.Show("Заполните баллы за третий экзамен", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try try
{ {
var model = new ExamPointsBindingModel var model = new ExamPointsBindingModel
@ -35,7 +43,8 @@ namespace StudentEnrollmentView
FirstExamPoints = Convert.ToInt32(textBoxFirstExamPoints.Text), FirstExamPoints = Convert.ToInt32(textBoxFirstExamPoints.Text),
SecondExamPoints = Convert.ToInt32(textBoxSecondExamPoints.Text), SecondExamPoints = Convert.ToInt32(textBoxSecondExamPoints.Text),
ThirdExamPoints = Convert.ToInt32(textBoxThirdExamPoints.Text), ThirdExamPoints = Convert.ToInt32(textBoxThirdExamPoints.Text),
AddPoints = Convert.ToInt32(textBoxAddPoints.Text), AddPoints = textBoxAddPoints.Text != string.Empty ? Convert.ToInt32(textBoxAddPoints.Text) : 0,
Summary = CalcSum(),
}; };
var operationResult = _logic.Create(model); var operationResult = _logic.Create(model);
if (!operationResult) if (!operationResult)
@ -57,5 +66,40 @@ namespace StudentEnrollmentView
DialogResult = DialogResult.Cancel; DialogResult = DialogResult.Cancel;
Close(); Close();
} }
private int CalcSum()
{
return Convert.ToInt32(textBoxFirstExamPoints.Text)
+ Convert.ToInt32(textBoxSecondExamPoints.Text)
+ Convert.ToInt32(textBoxThirdExamPoints.Text)
+ (textBoxAddPoints.Text != string.Empty ? Convert.ToInt32(textBoxAddPoints.Text) : 0);
}
private void FormExamPoints_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
if (Id != 0)
{
try
{
var view = _logic.ReadElement(new ExamPointsSearchModel
{
exampoints_id = Id,
});
textBoxFirstExamPoints.Text = view.FirstExamPoints.ToString();
textBoxSecondExamPoints.Text = view.SecondExamPoints.ToString();
textBoxThirdExamPoints.Text = view.ThirdExamPoints.ToString();
textBoxAddPoints.Text = view.AddPoints.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
} }
} }

View File

@ -10,16 +10,18 @@ namespace StudentEnrollmentView
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IStudentLogic _logic; private readonly IStudentLogic _logic;
private readonly IExamPointsLogic _examPointsLogic;
private int? _id; private int? _id;
private Dictionary<int, ICourseModel> _studentCourses; private Dictionary<int, ICourseModel> _studentCourses;
private IExamPointsModel _examPoints; private IExamPointsModel _examPoints;
public int Id { set { _id = value; } } public int Id { set { _id = value; } }
public FormStudent(ILogger<FormStudent> logger, IStudentLogic logic) public FormStudent(ILogger<FormStudent> logger, IStudentLogic logic, IExamPointsLogic examPointsLogic)
{ {
InitializeComponent(); InitializeComponent();
dataGridView.AllowUserToAddRows = false; dataGridView.AllowUserToAddRows = false;
_logger = logger; _logger = logger;
_logic = logic; _logic = logic;
_examPointsLogic = examPointsLogic;
_studentCourses = new Dictionary<int, ICourseModel>(); _studentCourses = new Dictionary<int, ICourseModel>();
} }
@ -42,6 +44,11 @@ namespace StudentEnrollmentView
textBoxEmail.Text = view.Email; textBoxEmail.Text = view.Email;
textBoxTIN.Text = view.TIN.ToString(); textBoxTIN.Text = view.TIN.ToString();
_studentCourses = view.StudentCourse ?? new Dictionary<int, ICourseModel>(); _studentCourses = view.StudentCourse ?? new Dictionary<int, ICourseModel>();
var test = _examPointsLogic.ReadElement(new ExamPointsSearchModel
{
exampoints_id = view.ExamPointsId,
});
_examPoints = test;
LoadData(); LoadData();
} }
} }
@ -62,7 +69,7 @@ namespace StudentEnrollmentView
dataGridView.Rows.Clear(); dataGridView.Rows.Clear();
foreach (var pc in _studentCourses) foreach (var pc in _studentCourses)
{ {
dataGridView.Rows.Add(new object[] { pc.Key, pc.Value }); dataGridView.Rows.Add(new object[] { pc.Key, pc.Value.name });
} }
} }
} }
@ -83,7 +90,7 @@ namespace StudentEnrollmentView
{ {
return; return;
} }
_logger.LogInformation("Добавление нового направления:{ CourseName}", form.CourseModel.CourseName); _logger.LogInformation("Добавление нового направления:{ CourseName}", form.CourseModel.name);
if (_studentCourses.ContainsKey(form.Id)) if (_studentCourses.ContainsKey(form.Id))
{ {
_studentCourses[form.Id] = form.CourseModel; _studentCourses[form.Id] = form.CourseModel;
@ -112,7 +119,7 @@ namespace StudentEnrollmentView
{ {
return; return;
} }
_logger.LogInformation("Изменение направления:{ CourseName }", form.CourseModel.CourseName); _logger.LogInformation("Изменение направления:{ CourseName }", form.CourseModel.name);
_studentCourses[form.Id] = form.CourseModel; _studentCourses[form.Id] = form.CourseModel;
LoadData(); LoadData();
} }
@ -205,7 +212,7 @@ namespace StudentEnrollmentView
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Ошибка сохранения цветов"); _logger.LogError(ex, "Ошибка сохранения студента");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }

View File

@ -28,7 +28,7 @@ namespace StudentEnrollmentView
} }
foreach (var elem in _list) foreach (var elem in _list)
{ {
if (elem.Id == Id) if (elem.course_id == Id)
{ {
return elem; return elem;
} }

View File

@ -1,4 +1,5 @@
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using StudentEnrollmentContracts.BindingModels;
using StudentEnrollmentContracts.BusinessLogicContracts; using StudentEnrollmentContracts.BusinessLogicContracts;
namespace StudentEnrollmentView namespace StudentEnrollmentView
@ -27,33 +28,76 @@ namespace StudentEnrollmentView
{ {
dataGridView.DataSource = list; dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false; dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["ExamPoints"].Visible = false; dataGridView.Columns["ExamPointsId"].Visible = false;
} dataGridView.Columns["StudentCourse"].Visible = false;
_logger.LogInformation("Загрузка компонентов"); }
_logger.LogInformation("Загрузка студентов");
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Ошибка загрузки компонентов"); _logger.LogError(ex, "Ошибка загрузки студентов");
} }
} }
private void buttonAdd_Click(object sender, EventArgs e) private void buttonAdd_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormStudent));
} if (service is FormStudent form)
{
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
private void buttonUpd_Click(object sender, EventArgs e) private void buttonUpd_Click(object sender, EventArgs e)
{ {
if (dataGridView.SelectedRows.Count == 1)
} {
var service = Program.ServiceProvider?.GetService(typeof(FormStudent));
if (service is FormStudent form)
{
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
}
private void buttonDel_Click(object sender, EventArgs e) private void buttonDel_Click(object sender, EventArgs e)
{ {
if (dataGridView.SelectedRows.Count == 1)
} {
if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
int id =
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Удаление записи");
try
{
if (!_logic.Delete(new StudentBindingModel
{
Id = id
}))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления записи");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void buttonRef_Click(object sender, EventArgs e) private void buttonRef_Click(object sender, EventArgs e)
{ {
LoadData();
} }
} }
} }