PIbd-31_Putincev.D.M._COP_29/COP/PortalAccountsDatabaseImplement/Implements/InterestStorage.cs

85 lines
2.8 KiB
C#

using PortalAccountsContracts.BindingModels;
using PortalAccountsContracts.SearchModels;
using PortalAccountsContracts.StoragesContracts;
using PortalAccountsContracts.ViewModels;
using PortalAccountsDatabaseImplement.Models;
namespace PortalAccountsDatabaseImplement.Implements
{
public class InterestStorage : IInterestStorage
{
public List<InterestViewModel> GetFullList()
{
using var context = new PortalAccountsDatabase();
return context.Interests
.Select(x => x.GetViewModel)
.ToList();
}
public List<InterestViewModel> GetFilteredList(InterestSearchModel model)
{
if (string.IsNullOrEmpty(model.Name))
{
return new();
}
using var context = new PortalAccountsDatabase();
return context.Interests
.Where(x => x.Name.Contains(model.Name))
.Select(x => x.GetViewModel)
.ToList();
}
public InterestViewModel? GetElement(InterestSearchModel model)
{
if (string.IsNullOrEmpty(model.Name) && !model.Id.HasValue)
{
return null;
}
using var context = new PortalAccountsDatabase();
return context.Interests
.FirstOrDefault(x => !string.IsNullOrEmpty(model.Name) && x.Name == model.Name ||
model.Id.HasValue && x.Id == model.Id)
?.GetViewModel;
}
public InterestViewModel? Insert(InterestBindingModel model)
{
var newInterest = Interest.Create(model);
if (newInterest == null)
{
return null;
}
using var context = new PortalAccountsDatabase();
context.Interests.Add(newInterest);
context.SaveChanges();
return newInterest.GetViewModel;
}
public InterestViewModel? Update(InterestBindingModel model)
{
using var context = new PortalAccountsDatabase();
var interest = context.Interests.FirstOrDefault(x => x.Id == model.Id);
if (interest == null)
{
return null;
}
interest.Update(model);
context.SaveChanges();
return interest.GetViewModel;
}
public InterestViewModel? Delete(InterestBindingModel model)
{
using var context = new PortalAccountsDatabase();
var element = context.Interests.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Interests.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}