PIbd-23_Nevaeva_K.A._Travel.../TravelCompany/TravelCompanyDatabaseImplement/Implements/ConditionStorage.cs

90 lines
3.3 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TravelCompanyContracts.BindingModels;
using TravelCompanyContracts.SearchModels;
using TravelCompanyContracts.StoragesContracts;
using TravelCompanyContracts.ViewModels;
using TravelCompanyDatabaseImplement.Models;
namespace TravelCompanyDatabaseImplement.Implements
{
public class ConditionStorage : IConditionStorage
{
public List<ConditionViewModel> GetFullList()
{
using var context = new TravelCompanyDatabase();
return context.Conditions
.Select(x => x.GetViewModel)
.ToList();
}
public List<ConditionViewModel> GetFilteredList(ConditionSearchModel model)
{
if (string.IsNullOrEmpty(model.ConditionName))
{
return new();
}
using var context = new TravelCompanyDatabase();
return context.Conditions
.Where(x => x.ConditionName.Contains(model.ConditionName))
.Select(x => x.GetViewModel)
.ToList();
}
public ConditionViewModel? GetElement(ConditionSearchModel model)
{
if (string.IsNullOrEmpty(model.ConditionName) && !model.Id.HasValue)
{
return null;
}
using var context = new TravelCompanyDatabase();
return context.Conditions
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.ConditionName) && x.ConditionName == model.ConditionName) ||
(model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public ConditionViewModel? Insert(ConditionBindingModel model)
{
var newCondition = Condition.Create(model);
if (newCondition == null)
{
return null;
}
using var context = new TravelCompanyDatabase();
context.Conditions.Add(newCondition);
context.SaveChanges();
return newCondition.GetViewModel;
}
public ConditionViewModel? Update(ConditionBindingModel model)
{
using var context = new TravelCompanyDatabase();
var condition = context.Conditions.FirstOrDefault(x => x.Id == model.Id);
if (condition == null)
{
return null;
}
condition.Update(model);
context.SaveChanges();
return condition.GetViewModel;
}
public ConditionViewModel? Delete(ConditionBindingModel model)
{
using var context = new TravelCompanyDatabase();
var element = context.Conditions.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Conditions.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}