using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; using VeterinaryContracts.BindingModels; using VeterinaryContracts.ViewModels; using VeterinaryDataModels.Models; using System.ComponentModel; namespace VeterinaryDatabaseImplement.Models { public class Pet : IPetModel { public int Id { get; private set; } [Required] public int OwnerId { get; private set; } public virtual Owner? Owner { get; private set; } [Required] public string PetName { get; private set; } = string.Empty; [Required] public string PetType { get; private set; } = string.Empty; [Required] public string PetBreed { get; private set; } = string.Empty; [Required] public string PetGender { get; private set; } = string.Empty; [Required] public int MedicationId { get; private set; } public virtual Medication? Medication { get; private set; } [ForeignKey("PetId")] public virtual List Visits { get; set; } = new(); [ForeignKey("PetId")] public virtual List Purchases { get; set; } = new(); public Dictionary? _visitPets = null; [NotMapped] public Dictionary VisitPets { get { if (_visitPets == null) { _visitPets = Visits.ToDictionary(recPC => recPC.VisitId, recPC => recPC.Visit as IVisitModel); } return _visitPets; } } public Dictionary? _purchasePets = null; [NotMapped] public Dictionary PurchasePets { get { if (_purchasePets == null) { _purchasePets = Purchases.ToDictionary(recPC => recPC.PurchaseId, recPC => recPC.Purchase as IPurchaseModel); } return _purchasePets; } } public static Pet? Create(PetBindingModel model) { if (model == null) { return null; } return new Pet() { Id = model.Id, PetName = model.PetName, PetType = model.PetType, PetBreed = model.PetBreed, PetGender = model.PetGender, OwnerId = model.OwnerId, MedicationId = model.MedicationId }; } public void Update(PetBindingModel? model) { if (model == null) { return; } PetName = model.PetName; PetType = model.PetType; PetBreed = model.PetBreed; PetGender = model.PetGender; } public PetViewModel GetViewModel => new() { Id = Id, PetName = PetName, PetType = PetType, PetBreed = PetBreed, PetGender = PetGender, OwnerId = OwnerId, }; public void UpdateVisits(VeterinaryDatabase context, PetBindingModel model) { var visitPets = context.VisitPets.Where(rec => rec.PetId == model.Id).ToList(); if (visitPets != null) { context.VisitPets.RemoveRange(visitPets.Where(rec => !model.VisitPets.ContainsKey(rec.VisitId))); context.SaveChanges(); foreach (var visit in visitPets) { model.VisitPets.Remove(visit.VisitId); } context.SaveChanges(); } var pet = context.Pets.First(x => x.Id == Id); foreach (var pc in model.VisitPets) { context.VisitPets.Add(new VisitPet { Pet = pet, Visit = context.Visits.First(x => x.Id == pc.Key), }); context.SaveChanges(); } _visitPets = null; } } }