using LawCompanyDataModels.Enums; using LawCompanyDataModels.Models; using LawCompanyContracts.BindingModels; using LawCompanyContracts.ViewModels; using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; namespace LawCompanyDatabaseImplement.Models { public class Case : ICaseModel { public int Id { get; private set; } [Required] public string Name { get; private set; } = String.Empty; [Required] public string CaseType { get; private set; } = String.Empty; [Required] public DateTime DateCreate { get; private set; } public DateTime? DateImplement { get; private set; } [Required] public CaseStatus Status { get; private set; } private Dictionary? _caseClients = null; [NotMapped] public Dictionary CaseClients { get { if (_caseClients == null) { using var context = new LawCompanyDatabase(); _caseClients = Clients .ToDictionary(x => x.ClientId, x => (context.Clients.FirstOrDefault(y => y.Id == x.ClientId) as IClientModel)); } return _caseClients; } } [ForeignKey("CaseId")] public virtual List Clients { get; set; } = new(); [ForeignKey("CaseId")] public virtual List Hearings { get; set; } = new(); public static Case Create(LawCompanyDatabase context, CaseBindingModel model) { if (model == null) { return null; } return new Case() { Id = model.Id, Name = model.Name, DateCreate = model.DateCreate, DateImplement = model.DateImplement, Status = model.Status, Clients = model.CaseClients.Select(x => new CaseClient { Client = context.Clients.First(y => y.Id == x.Key) }).ToList() }; } public void Update(CaseBindingModel? model) { using var context = new LawCompanyDatabase(); if (model == null) { return; } if (model.Status == CaseStatus.ЗакрытиеДела) DateImplement = DateTime.Now; Name = model.Name; Status = model.Status; if (model.DateImplement.HasValue) DateImplement = model.DateImplement; if (!model.CompanyId.HasValue) CompanyId = model.CompanyId; } public CaseViewModel GetViewModel => new() { Id = Id, Name = Name, CaseType = CaseType, DateCreate = DateCreate, DateImplement = DateImplement, Status = Status, CaseClients = CaseClients, }; public void UpdateClients(LawCompanyDatabase context, CaseBindingModel model) { var caseClients = context.CaseClients.Where(rec => rec.CaseId == model.Id).ToList(); if (caseClients != null && caseClients.Count > 0) { // удалили те, которых нет в модели context.CaseClients.RemoveRange(caseClients.Where(rec => !model.CaseClients.ContainsKey(rec.ClientId))); context.SaveChanges(); } var _case = context.Cases.First(x => x.Id == Id); foreach (var pc in model.CaseClients) { if (!CaseClients.ContainsKey(pc.Key)) { context.CaseClients.Add(new CaseClient { Case = _case, Client = context.Clients.First(x => x.Id == pc.Key), }); } context.SaveChanges(); } _caseClients = null; } } }