SUBD_SchoolSchedule/SchoolSchedule/SchoolScheduleDataBaseImplement/Models/Student.cs
2024-04-08 23:45:46 +04:00

106 lines
3.1 KiB
C#

using SchoolScheduleContracts.BindingModels;
using SchoolScheduleContracts.ViewModels;
using SchoolScheduleDataModels.Enums;
using SchoolScheduleDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SchoolScheduleDataBaseImplement.Models
{
public class Student : IStudentModel
{
public int Id { get; private set; }
[Required]
public string FullName { get; private set; }
[Required]
public int GradeId { get; private set; }
public virtual Grade Grade { get; set; } = new();
private Dictionary<int, (ILessonModel, StudentStatus, int?)> _attendance = null;
[NotMapped]
public Dictionary<int, (ILessonModel, StudentStatus, int?)> Attendance
{
get
{
if (_attendance == null)
{
_attendance = Lessons.ToDictionary(recPC => recPC.LessonId, recPC =>
(recPC.Lesson as ILessonModel, recPC.Status, recPC.Mark));
}
return _attendance;
}
}
[ForeignKey("StudentId")]
public virtual List<LessonStudent> Lessons { get; set; } = new();
public static Student Create(SchoolScheduleDataBase context, StudentBindingModel model)
{
return new Student()
{
Id = model.Id,
FullName = model.FullName,
GradeId = model.GradeId,
Grade = context.Grades.First(y => y.Id == model.GradeId),
Lessons = model.Attendance.Select(x => new LessonStudent
{
Lesson = context.Lessons.First(y => y.Id == x.Key),
Status = x.Value.Item2,
Mark = x.Value.Item3,
}).ToList(),
};
}
public void Update(SchoolScheduleDataBase context, StudentBindingModel model)
{
FullName = model.FullName;
GradeId = model.GradeId;
Grade = context.Grades.First(y => y.Id == model.GradeId);
}
public StudentViewModel GetViewModel => new()
{
Id = Id,
FullName = FullName,
GradeId = GradeId,
GradeName = Grade.Year.ToString() + Grade.Letter.ToString(),
Attendance = Attendance
};
public void UpdateAttendance(SchoolScheduleDataBase context, StudentBindingModel model)
{
var attendance = context.LessonStudents.Where(rec => (rec.StudentId == model.Id)).ToList();
if (attendance != null && attendance.Count > 0)
{
context.LessonStudents.RemoveRange(attendance.Where(rec
=> !model.Attendance.ContainsKey(rec.LessonId)));
context.SaveChanges();
foreach (var updateComponent in attendance)
{
updateComponent.Status = model.Attendance[updateComponent.LessonId].Item2;
updateComponent.Mark = model.Attendance[updateComponent.LessonId].Item3;
model.Attendance.Remove(updateComponent.LessonId);
}
context.SaveChanges();
}
var student = context.Students.First(x => x.Id == Id);
foreach (var pc in model.Attendance)
{
context.LessonStudents.Add(new LessonStudent
{
Student = student,
Lesson = context.Lessons.First(x => x.Id == pc.Key),
Mark = pc.Value.Item3,
Status = pc.Value.Item2,
});
context.SaveChanges();
}
_attendance = null;
}
}
}