using LawCompanyContracts.BindingModels; using LawCompanyContracts.ViewModels; using LawCompanyDatabaseImplement.Models; using LawCompanyDataModels.Models; using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; namespace LawCompanyDatabaseImplement.Models { public class Consultation : IConsultationModel { public int Id { get; private set; } [Required] public double Cost { get; private set; } [Required] public DateTime ConsultationDate { get; private set; } public int? CaseId { get; private set; } public Case Case { get; private set; } public int GuarantorId { get; set; } private Dictionary _consultationLawyers = null; [ForeignKey("ConsultationId")] public virtual List Lawyers { get; set; } = new(); [NotMapped] public Dictionary ConsultationLawyers { get { if (_consultationLawyers == null) { _consultationLawyers = Lawyers.ToDictionary(x => x.LawyerId, x => (x.Lawyer as ILawyerModel)); } return _consultationLawyers; } } public static Consultation? Create(LawCompanyDatabase context, ConsultationBindingModel? model) { if (model == null) { return null; } return new Consultation() { Id = model.Id, Cost = model.Cost, ConsultationDate = model.ConsultationDate, CaseId = model.CaseId, GuarantorId = model.GuarantorId, Lawyers = model.ConsultationLawyers.Select(x => new ConsultationLawyer { Lawyer = context.Lawyers.First(y => y.Id == x.Key) }).ToList() }; } public void Update(ConsultationBindingModel? model) { using var context = new LawCompanyDatabase(); if (model == null) { return; } Cost = model.Cost; ConsultationDate = model.ConsultationDate; CaseId = model.CaseId; } public ConsultationViewModel GetViewModel => new() { Id = Id, Cost = Cost, ConsultationDate = ConsultationDate, CaseId = CaseId, }; public void UpdateLawyers(LawCompanyDatabase context, ConsultationBindingModel model) { var consultationLawyers = context.ConsultationLawyers.Where(rec => rec.ConsultationId == model.Id).ToList(); if (consultationLawyers != null && consultationLawyers.Count > 0) { context.ConsultationLawyers.RemoveRange(consultationLawyers.Where(rec => !model.ConsultationLawyers.ContainsKey(rec.LawyerId))); context.SaveChanges(); foreach (var updateMember in consultationLawyers) { model.ConsultationLawyers.Remove(updateMember.LawyerId); } context.SaveChanges(); } var _consultation = context.Consultations.First(x => x.Id == Id); foreach (var pc in model.ConsultationLawyers) { context.ConsultationLawyers.Add(new ConsultationLawyer { Consultation = _consultation, Lawyer = context.Lawyers.First(x => x.Id == pc.Key), }); context.SaveChanges(); } _consultationLawyers = null; } } }