using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Numerics; using System.Text; using System.Threading.Tasks; using VeterinaryClinicContracts.BindingModels; using VeterinaryClinicContracts.ViewModels; using VeterinaryClinicDataModels.Models; namespace VeterinaryClinicDatabaseImplement.Models { public class Animal: IAnimalModel { public int Id { get; set; } [Required] public string Type { get; set; } = string.Empty; [Required] public string Breed { get; set; } = string.Empty; [Required] public int Age { get; set; } [ForeignKey("UserId")] public int UserId { get; set; } public virtual User User { get; set; } = new(); [ForeignKey("AnimalId")] public virtual List Medications { get; set; } = new(); private Dictionary? _animalMedications = null; [NotMapped] public Dictionary AnimalMedications { get { if(_animalMedications == null) _animalMedications = Medications.ToDictionary(recAM => recAM.MedicationId, recAM => (recAM.Medication as IMedicationModel)); return _animalMedications; } } public static Animal? Create(VeterinaryClinicDatabase context, AnimalBindingModel model) { if (model == null) { return null; } return new Animal() { Id = model.Id, Type = model.Type, Breed = model.Breed, Age = model.Age, UserId = model.UserId, User = context.Users .First(x => x.Id == model.UserId), Medications = model.AnimalMedications.Select(x => new AnimalMedication { Medication = context.Medications.First(y => y.Id == x.Key) }).ToList() }; } public void Update(AnimalBindingModel model) { if (model == null) { return; } Type = model.Type; Breed = model.Breed; Age = model.Age; } public AnimalViewModel GetViewModel => new() { Id = Id, Type = Type, Breed = Breed, Age = Age, UserId = UserId, UserFullName = User.FullName, AnimalMedications = AnimalMedications }; public void UpdateMedications(VeterinaryClinicDatabase context, AnimalBindingModel model) { var animalMedications = context.AnimalMedications.Where(rec => rec.AnimalId == model.Id).ToList(); context.AnimalMedications.RemoveRange(animalMedications); context.SaveChanges(); var animal = context.Animals.First(x => x.Id == Id); foreach (var pr in model.AnimalMedications) { context.AnimalMedications.Add(new AnimalMedication { Animal = animal, Medication = context.Medications.First(x => x.Id == pr.Key) }); context.SaveChanges(); } _animalMedications = null; } } }