PIbd-22_Filippov_D.S._Cours.../VeterinaryDatabaseImplement/Implements/OwnerStorage.cs

85 lines
2.7 KiB
C#
Raw Permalink Normal View History

2024-05-30 07:33:38 +04:00
using Microsoft.EntityFrameworkCore;
using VeterinaryContracts.BindingModels;
using VeterinaryContracts.SearchModels;
using VeterinaryContracts.StorageContracts;
using VeterinaryContracts.ViewModels;
using VeterinaryDatabaseImplement.Models;
namespace VeterinaryDatabaseImplement.Implements
{
public class OwnerStorage : IOwnerStorage
{
public List<OwnerViewModel> GetFullList()
{
using var context = new VeterinaryDatabase();
return context.Owners
.Select(x => x.GetViewModel)
.ToList();
}
public List<OwnerViewModel> GetFilteredList(OwnerSearchModel model)
{
if (string.IsNullOrEmpty(model.OwnerFIO) && string.IsNullOrEmpty(model.Login) && string.IsNullOrEmpty(model.Password))
{
return new();
}
using var context = new VeterinaryDatabase();
return context.Owners
.Where(x => (string.IsNullOrEmpty(model.OwnerFIO) || x.OwnerFIO.Contains(model.OwnerFIO) &&
(string.IsNullOrEmpty(model.Login) || x.Login.Contains(model.Login)) &&
(string.IsNullOrEmpty(model.Password) || x.Password.Contains(model.Password))))
.Select(x => x.GetViewModel)
.ToList();
}
public OwnerViewModel? GetElement(OwnerSearchModel model)
{
if (string.IsNullOrEmpty(model.OwnerFIO) && string.IsNullOrEmpty(model.Login) && string.IsNullOrEmpty(model.Password) &&
!model.Id.HasValue)
{
return null;
}
using var context = new VeterinaryDatabase();
return context.Owners
.FirstOrDefault(x => (string.IsNullOrEmpty(model.OwnerFIO) || x.OwnerFIO == model.OwnerFIO) &&
(!model.Id.HasValue || x.Id == model.Id) && (string.IsNullOrEmpty(model.Login) || x.Login == model.Login) &&
(string.IsNullOrEmpty(model.Password) || x.Password == model.Password))
?.GetViewModel;
}
public OwnerViewModel? Insert(OwnerBindingModel model)
{
var newOwner = Owner.Create(model);
if (newOwner == null)
{
return null;
}
using var context = new VeterinaryDatabase();
context.Owners.Add(newOwner);
context.SaveChanges();
return newOwner.GetViewModel;
}
public OwnerViewModel? Update(OwnerBindingModel model)
{
using var context = new VeterinaryDatabase();
var client = context.Owners.FirstOrDefault(x => x.Id == model.Id);
if (client == null)
{
return null;
}
client.Update(model);
context.SaveChanges();
return client.GetViewModel;
}
public OwnerViewModel? Delete(OwnerBindingModel model)
{
using var context = new VeterinaryDatabase();
var element = context.Owners.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Owners.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}