Rogashova_E.A._CourseWork_H.../HospitalDataBaseImplements/Implements/MedicinesStorage.cs

87 lines
2.9 KiB
C#
Raw Normal View History

using HospitalContracts.BindingModels;
using HospitalContracts.SearchModels;
using HospitalContracts.StoragesContracts;
using HospitalContracts.ViewModels;
using HospitalDataBaseImplements.Models;
using System;
2023-04-05 23:24:58 +04:00
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HospitalDataBaseImplements.Implements
{
public class MedicinesStorage : IMedicinesStorage
2023-04-05 23:24:58 +04:00
{
public List<MedicinesViewModel> GetFullList()
{
using var context = new HospitalDatabase();
return context.Medicines
.Select(x => x.GetViewModel)
.ToList();
}
public List<MedicinesViewModel> GetFilteredList(MedicinesSearchModel model)
{
if (string.IsNullOrEmpty(model.MedicinesName))
{
return new();
}
using var context = new HospitalDatabase();
return context.Medicines
.Where(x => x.MedicinesName.Contains(model.MedicinesName))
.Select(x => x.GetViewModel)
.ToList();
}
public MedicinesViewModel? GetElement(MedicinesSearchModel model)
{
if (string.IsNullOrEmpty(model.MedicinesName) && !model.Id.HasValue)
{
return null;
}
using var context = new HospitalDatabase();
return context.Medicines
.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.MedicinesName) && x.MedicinesName ==
model.MedicinesName) ||
(model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public MedicinesViewModel? Insert(MedicinesBindingModel model)
{
var newMedicine = Medicines.Create(model);
if (newMedicine == null)
{
return null;
}
using var context = new HospitalDatabase();
context.Medicines.Add(newMedicine);
context.SaveChanges();
return newMedicine.GetViewModel;
}
public MedicinesViewModel? Update(MedicinesBindingModel model)
{
using var context = new HospitalDatabase();
var medicine = context.Medicines.FirstOrDefault(x => x.Id == model.Id);
if (medicine == null)
{
return null;
}
medicine.Update(model);
context.SaveChanges();
return medicine.GetViewModel;
}
public MedicinesViewModel? Delete(MedicinesBindingModel model)
{
using var context = new HospitalDatabase();
var element = context.Medicines.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Medicines.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
2023-04-05 23:24:58 +04:00
}
}