using LawFimDataModels.Enums; using LawFimDataModels.Models; using LawFirmContracts.BindingModels; using LawFirmContracts.ViewModels; using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; using System.ComponentModel.Design; namespace LawFirmDatabaseImplement.Models { public class Hearing :IHearingModel { public int Id { get; private set; } [Required] public DateTime HearingDate { get; private set; } [Required] public string Judge{ get; private set; } = string.Empty; public int GuarantorId { get; set; } private Dictionary? _hearingLawyers = null; [NotMapped] public Dictionary HearingLawyers { get { if (_hearingLawyers == null) { using var context = new LawFirmDatabase(); _hearingLawyers = Lawyers .ToDictionary(x => x.LawyerId, x => (context.Lawyers .FirstOrDefault(y => y.Id == x.LawyerId) as ILawyerModel)); } return _hearingLawyers; } } [ForeignKey("HearingId")] public virtual List Lawyers { get; set; } = new(); public static Hearing? Create(LawFirmDatabase context, HearingBindingModel? model) { if (model == null) { return null; } return new Hearing() { Id = model.Id, HearingDate = model.HearingDate, Judge = model.Judge, GuarantorId = model.GuarantorId, Lawyers = model.HearingLawyers.Select(x => new HearingLawyer { Lawyer = context.Lawyers.First(y => y.Id == x.Key) }).ToList() }; } public void Update(HearingBindingModel? model) { if (model == null) { return; } HearingDate = model.HearingDate; Judge = model.Judge; } public HearingViewModel GetViewModel => new() { Id = Id, HearingDate = HearingDate, Judge = Judge, GuarantorId = GuarantorId, HearingLawyers = HearingLawyers }; public void UpdateLawyers(LawFirmDatabase context, HearingBindingModel model) { var hearingLawyer = context.HearingLawyers .Where(rec => rec.HearingId == model.Id) .ToList(); if (hearingLawyer != null && hearingLawyer.Count > 0) { context.HearingLawyers.RemoveRange(hearingLawyer.Where(rec => !model.HearingLawyers.ContainsKey(rec.LawyerId))); context.SaveChanges(); } var _hearing = context.Hearings.First(x => x.Id == Id); foreach (var pc in model.HearingLawyers) { if (!HearingLawyers.ContainsKey(pc.Key)) { context.HearingLawyers.Add(new HearingLawyer { Hearing = _hearing, Lawyer = context.Lawyers.First(x => x.Id == pc.Key), }); } context.SaveChanges(); } _hearingLawyers = null; } } }