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

78 lines
2.5 KiB
C#

using VeterinaryContracts.BindingModels;
using VeterinaryContracts.SearchModels;
using VeterinaryContracts.StorageContracts;
using VeterinaryContracts.ViewModels;
using VeterinaryDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
namespace VeterinaryDatabaseImplement.Implements
{
public class VisitStorage : IVisitStorage
{
public List<VisitViewModel> GetFullList()
{
using var context = new VeterinaryDatabase();
return context.Visits.Include(x => x.Pets).ThenInclude(x => x.Pet).Include(x => x.Owner)
.Include(x => x.Doctor).Select(x => x.GetViewModel)
.ToList();
}
public List<VisitViewModel> GetFilteredList(VisitSearchModel model)
{
using var context = new VeterinaryDatabase();
return context.Visits.Where(x => x.OwnerId == model.OwnerId).Include(x => x.Owner).Include(x => x.Pets).ThenInclude(x => x.Pet).Include(x => x.Doctor)
.Where(x => String.IsNullOrEmpty(model.VisitName) || x.VisitName.Contains(model.VisitName)).ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public VisitViewModel? GetElement(VisitSearchModel model)
{
if (string.IsNullOrEmpty(model.VisitName) && !model.Id.HasValue)
{
return null;
}
using var context = new VeterinaryDatabase();
return context.Visits.Include(x => x.Owner).Include(x => x.Pets).ThenInclude(x => x.Pet).Include(x => x.Doctor)
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.VisitName) && x.VisitName == model.VisitName) || (x.Id == model.Id))?.GetViewModel;
}
public VisitViewModel? Insert(VisitBindingModel model)
{
using var context = new VeterinaryDatabase();
var newVisit = Visit.Create(context, model);
if (newVisit == null)
{
return null;
}
context.Visits.Add(newVisit);
context.SaveChanges();
return newVisit.GetViewModel;
}
public VisitViewModel? Update(VisitBindingModel model)
{
using var context = new VeterinaryDatabase();
var visit = context.Visits.Include(x => x.Pets).ThenInclude(x => x.Pet).Include(x => x.Owner)
.FirstOrDefault(x => x.Id == model.Id);
if (visit == null)
{
return null;
}
visit.Update(model);
context.SaveChanges();
return visit.GetViewModel;
}
public VisitViewModel? Delete(VisitBindingModel model)
{
using var context = new VeterinaryDatabase();
var element = context.Visits.Include(x => x.Owner).Include(x => x.Pets).Include(x => x.Doctor).FirstOrDefault
(rec => rec.Id == model.Id);
if (element != null)
{
context.Visits.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}