PIbd-21_Pyatakov_KM_Markov_.../UniversityDataBaseImplemet/Models/Stream.cs

95 lines
3.1 KiB
C#
Raw Normal View History

2023-04-08 13:59:34 +04:00
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using UniversityContracts.BindingModels;
using UniversityContracts.ViewModels;
using UniversityModels.Models;
namespace UniversityDataBaseImplemet.Models
{
public class Stream : IStreamModel
{
[Required]
public string Name { get; set; } = string.Empty;
[Required]
public int Course { get; set; }
[Required]
public int UserId { get; set; }
public int Id { get; private set; }
[ForeignKey("StreamId")]
public virtual List<EducationGroupStream> EducationGroupStream { get; set; } = new();
[ForeignKey("StreamId")]
public virtual List<StudentStream> StreamStudents { get; set; } = new();
public virtual User User { get; set; }
2023-04-08 20:16:42 +04:00
private Dictionary<int, IStudentModel>? _studentStream = null;
[NotMapped]
public Dictionary<int, IStudentModel> StudentStream
{
get
{
if (_studentStream == null)
{
_studentStream = StreamStudents.ToDictionary(rec => rec.StudentId, rec => rec.Student as IStudentModel);
}
return _studentStream;
}
}
2023-04-08 13:59:34 +04:00
public static Stream Create(StreamBindingModel model)
{
return new Stream()
{
Id = model.Id,
Name = model.Name,
Course = model.Course,
UserId = model.UserId
};
}
public void Update(StreamBindingModel model)
{
Name = model.Name;
Course = model.Course;
UserId = model.UserId;
}
2023-04-08 20:16:42 +04:00
public void UpdateStreamStudents(Database context, StreamBindingModel model)
{
var studentStream = context.StudentStreams
.Where(rec => rec.StreamId == model.Id)
.ToList();
if (studentStream != null)
{
context.StudentStreams
.RemoveRange(studentStream
.Where(rec => !model.StudentStream
.ContainsKey(rec.StudentId))
);
context.SaveChanges();
var stream = context.Streams
.First(x => x.Id == Id);
foreach (var sd in studentStream)
{
model.StudentStream.Remove(sd.StudentId);
}
foreach (var sd in model.StudentStream)
{
context.StudentStreams.Add(new StudentStream
{
Stream = stream,
Student = context.Students.First(x => x.Id == sd.Key),
});
context.SaveChanges();
}
_studentStream = null;
}
}
2023-04-08 13:59:34 +04:00
public StreamViewModel GetViewModel => new()
{
Id = Id,
Name = Name,
UserId = UserId,
Course= Course
};
}
}