94 lines
3.5 KiB
C#
94 lines
3.5 KiB
C#
using LawFirmContracts.BindingModels;
|
||
using LawFirmContracts.ViewModels;
|
||
using LawFirmDataModels.Models;
|
||
using System.ComponentModel.DataAnnotations;
|
||
using System.ComponentModel.DataAnnotations.Schema;
|
||
|
||
namespace LawFirmDatabaseImplement.Models
|
||
{
|
||
public class Document : IDocumentModel
|
||
{
|
||
public int Id { get; set; }
|
||
[Required]
|
||
public string DocumentName { get; set; } = string.Empty;
|
||
[Required]
|
||
public double Price { get; 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)
|
||
{
|
||
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 UpdateBlanks(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;
|
||
}
|
||
}
|
||
} |