PIbd-22_Filippov_D.S._Cours.../VeterinaryDatabaseImplement/Models/Visit.cs
2024-05-30 07:33:38 +04:00

109 lines
2.8 KiB
C#

using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using VeterinaryContracts.BindingModels;
using VeterinaryContracts.ViewModels;
using VeterinaryDataModels.Models;
namespace VeterinaryDatabaseImplement.Models
{
public class Visit : IVisitModel
{
public int Id { get; private set; }
[Required]
public int OwnerId { get; private set; }
public virtual Owner? Owner { get; private set; }
[Required]
public int DoctorId { get; private set; }
public virtual Doctor? Doctor { get; private set; }
[Required]
public string VisitName { get; private set; } = string.Empty;
[Required]
public DateTime DateVisit { get; private set; }
private Dictionary<int, IPetModel>? _visitPet = null;
[NotMapped]
public Dictionary<int, IPetModel> VisitPet
{
get
{
if (_visitPet == null)
{
_visitPet = Pets
.ToDictionary(recPC => recPC.PetId, recPC =>
(recPC.Pet as IPetModel));
}
return _visitPet;
}
}
[ForeignKey("VisitId")]
public virtual List<VisitPet> Pets { get; set; } = new();
public static Visit? Create(VeterinaryDatabase context, VisitBindingModel model)
{
return new Visit()
{
Id = model.Id,
OwnerId = model.OwnerId,
DoctorId = model.DoctorId,
//ServiceId = model.ServiceId,
VisitName = model.VisitName,
DateVisit = model.DateVisit,
Pets = model.VisitPet.Select(x => new VisitPet
{
Pet = context.Pets.First(y => y.Id == x.Key),
}).ToList()
};
}
public void Update(VisitBindingModel? model)
{
if (model == null)
{
return;
}
VisitName = model.VisitName;
}
public VisitViewModel GetViewModel => new()
{
Id = Id,
OwnerId = OwnerId,
VisitName = VisitName,
DoctorId = DoctorId,
DoctorName = Doctor?.DoctorFIO ?? string.Empty,
DateVisit = DateVisit,
//ServiceId = ServiceId,
//VisitName = Visit?.VisitName ?? string.Empty,
//VisitPet = VisitPet,
};
//public void UpdateVisits(VeterinaryDatabase context, VisitBindingModel model)
//{
// if (model.VisitPet == null)
// return;
// var visitPets = context.VisitPets.Where(rec => rec.VisitId == model.Id).ToList();
// if (visitPets != null && visitPets.Count > 0)
// {
// context.VisitPets.RemoveRange(visitPets.Where(rec => !model.VisitPet.ContainsKey(rec.VisitId)));
// context.SaveChanges();
// foreach (var updatePet in visitPets)
// {
// model.VisitPet.Remove(updatePet.PetId);
// }
// context.SaveChanges();
// }
// var visit = context.Visits.First(x => x.Id == Id);
// foreach (var pc in model.VisitPet)
// {
// context.VisitPets.Add(new VisitPet
// {
// Visit = visit,
// Pet = context.Pets.First(x => x.Id == pc.Key),
// });
// context.SaveChanges();
// }
// _visitPet = null;
//}
}
}