using LawFirmContracts.BindingModels; using LawFirmContracts.ViewModels; using LawFirmDataModels.Models; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LawFirmDatabaseImplement.Models { public class Document : IDocumentModel { public int Id { get; private set; } [Required] public string DocumentName { get; private set; } = string.Empty; [Required] public double Price { get; private set; } private Dictionary? _documentBlanks = null; [NotMapped] public Dictionary DocumentBlanks { get { if (_documentBlanks == null) { _documentBlanks = Blanks.ToDictionary(recPC => recPC.BlankId, recPC => (recPC.Blank as IBlankModel, recPC.Count)); } return _documentBlanks; } } [ForeignKey("DocumentId")] public virtual List Blanks { get; set; } = new(); [ForeignKey("DocumentId")] public virtual List Orders { get; set; } = new(); public static Document? Create(LawFirmDatabase context, DocumentBindingModel model) { var blanks = context.Blanks; return new Document() { Id = model.Id, DocumentName = model.DocumentName, Price = model.Price, Blanks = model.DocumentBlanks.Select(x => new DocumentBlank { Blank = context.Blanks.First(y => y.Id == x.Key), Count = x.Value.Item2 }).ToList() }; } public void Update(DocumentBindingModel model) { DocumentName = model.DocumentName; Price = model.Price; } public DocumentViewModel GetViewModel => new() { Id = Id, DocumentName = DocumentName, Price = Price, DocumentBlanks = DocumentBlanks }; public void UpdateComponents(LawFirmDatabase context, DocumentBindingModel model) { var documentBlanks = context.DocumentBlanks.Where(rec => rec.DocumentId == model.Id).ToList(); if (documentBlanks != null && documentBlanks.Count > 0) { // удалили те, которых нет в модели context.DocumentBlanks.RemoveRange(documentBlanks.Where(rec => !model.DocumentBlanks.ContainsKey(rec.BlankId))); context.SaveChanges(); // обновили количество у существующих записей foreach (var updateBlank in documentBlanks) { updateBlank.Count = model.DocumentBlanks[updateBlank.BlankId].Item2; model.DocumentBlanks.Remove(updateBlank.BlankId); } context.SaveChanges(); } var document = context.Documents.First(x => x.Id == Id); foreach (var pc in model.DocumentBlanks) { context.DocumentBlanks.Add(new DocumentBlank { Document = document, Blank = context.Blanks.First(x => x.Id == pc.Key), Count = pc.Value.Item2 }); context.SaveChanges(); } _documentBlanks = null; } } }