using LawCompanyDataModels.Models; using LawCompanyContracts.BindingModels; using LawCompanyContracts.ViewModels; using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; namespace LawCompanyDatabaseImplement.Models { public class Visit : IVisitModel { public int Id { get; private set; } [Required] public DateTime VisitDate { get; private set; } //связь один-к-одному public int? HearingId { get; private set; } public Hearing Hearing { get; set; } = null!; //--- public int ExecutorId { get; set; } private Dictionary? _visitClients = null; [NotMapped] public Dictionary VisitClients { get { if (_visitClients == null) { _visitClients = Clients.ToDictionary(x => x.ClientId, x => (x.Client as IClientModel)); } return _visitClients; } } [ForeignKey("VisitId")] public virtual List Clients { get; set; } = new(); public static Visit Create(LawCompanyDatabase context, VisitBindingModel model) { return new Visit() { Id = model.Id, VisitDate = model.VisitDate, HearingId = model.HearingId, ExecutorId = model.ExecutorId, Clients = model.VisitClients.Select(x => new VisitClient { Client = context.Clients.First(y => y.Id == x.Key) }).ToList() }; } public void Update(VisitBindingModel model) { VisitDate = model.VisitDate; HearingId = model.HearingId; } public VisitViewModel GetViewModel => new() { Id = Id, VisitDate = VisitDate, HearingId = HearingId, ExecutorId = ExecutorId, }; public void UpdateClients(LawCompanyDatabase context, VisitBindingModel model) { var visitClients = context.VisitClients.Where(rec => rec.VisitId == model.Id).ToList(); if (visitClients != null && visitClients.Count > 0) { // удалили те, которых нет в модели context.VisitClients.RemoveRange(visitClients.Where(rec => !model.VisitClients.ContainsKey(rec.ClientId))); context.SaveChanges(); foreach (var updateLunch in visitClients) { model.VisitClients.Remove(updateLunch.ClientId); } context.SaveChanges(); } var _visit = context.Visits.First(x => x.Id == Id); foreach (var pc in model.VisitClients) { context.VisitClients.Add(new VisitClient { Visit = _visit, Client = context.Clients.First(x => x.Id == pc.Key), }); context.SaveChanges(); } _visitClients = null; } } }