using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using VeterinaryContracts.BindingModels; using VeterinaryContracts.ViewModels; using VeterinaryDataModels.Models; namespace VeterinaryDatabaseImplement.Models { public class Purchase : IPurchaseModel { public int Id { get; private set; } [Required] public int OwnerId { get; private set; } public virtual Owner? Owner { get; private set; } [Required] public string PuchaseName { get; private set; } = string.Empty; [Required] public int DrugId { get; private set; } public virtual Drug? Drug { get; private set; } [Required] public int Count { get; private set; } [Required] public double Sum { get; private set; } [Required] public DateTime DateCreate { get; private set; } private Dictionary? _purchasePet = null; [NotMapped] public Dictionary PurchasePet { get { if (_purchasePet == null) { _purchasePet = Pets .ToDictionary(recPC => recPC.PetId, recPC => (recPC.Pet as IPetModel)); } return _purchasePet; } } [ForeignKey("PurchaseId")] public virtual List Pets { get; set; } = new(); public static Purchase? Create(VeterinaryDatabase context, PurchaseBindingModel model) { return new Purchase() { Id = model.Id, OwnerId = model.OwnerId, DrugId = model.DrugId, DateCreate = model.DateCreate, PuchaseName = model.PuchaseName, Pets = model.PurchasePet.Select(x => new PurchasePet { Pet = context.Pets.First(y => y.Id == x.Key), }).ToList() }; } public PurchaseViewModel GetViewModel => new() { Id = Id, Count = Count, Sum = Sum, OwnerId = OwnerId, DrugId = DrugId, PuchaseName = PuchaseName, DrugName = Drug?.DrugName ?? string.Empty, DateCreate = DateCreate }; } }