PIbd-21_Danilov_V.V._Course.../VeterinaryClinic/VeterinaryClinicDatabaseImplement/Models/Animal.cs

117 lines
3.6 KiB
C#
Raw Normal View History

2024-04-30 23:14:53 +04:00
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<AnimalMedication> Medications { get; set; } = new();
private Dictionary<int, IMedicationModel>? _animalMedications { get; set; } = new();
[NotMapped]
public Dictionary<int, IMedicationModel> 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();
if (animalMedications != null && animalMedications.Count > 0)
{
context.AnimalMedications.RemoveRange(animalMedications.Where(rec => !model.AnimalMedications.ContainsKey(rec.MedicationId)));
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;
}
}
}