PIbd-23_Mochalov_D.V._LawFirm/LawFirm/LawFirmDatabaseImplement/Models/Document.cs

103 lines
3.6 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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<int, (IBlankModel, int)>? _documentBlanks = null;
[NotMapped]
public Dictionary<int, (IBlankModel, int)> 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<DocumentBlank> Blanks { get; set; } = new();
[ForeignKey("DocumentId")]
public virtual List<Order> 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;
}
}
}