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

112 lines
3.7 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TravelCompanyContracts.StoragesContracts;
using TravelCompanyContracts.BindingModels;
using TravelCompanyContracts.SearchModels;
using TravelCompanyContracts.ViewModels;
using TravelCompanyDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
namespace TravelCompanyDatabaseImplement.Implements
{
public class TravelStorage : ITravelStorage
{
public List<TravelViewModel> GetFullList()
{
using var context = new TravelCompanyDatabase();
return context.Travels
.Include(x => x.Conditions)
.ThenInclude(x => x.Condition)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public List<TravelViewModel> GetFilteredList(TravelSearchModel model)
{
if (string.IsNullOrEmpty(model.TravelName))
{
return new();
}
using var context = new TravelCompanyDatabase();
return context.Travels
.Include(x => x.Conditions)
.ThenInclude(x => x.Condition)
.Where(x => x.TravelName.Contains(model.TravelName))
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public TravelViewModel? GetElement(TravelSearchModel model)
{
if (string.IsNullOrEmpty(model.TravelName) && !model.Id.HasValue)
{
return null;
}
using var context = new TravelCompanyDatabase();
return context.Travels
.Include(x => x.Conditions)
.ThenInclude(x => x.Condition)
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.TravelName) && x.TravelName == model.TravelName) ||
(model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public TravelViewModel? Insert(TravelBindingModel model)
{
using var context = new TravelCompanyDatabase();
var newTravel = Travel.Create(context, model);
if (newTravel == null)
{
return null;
}
context.Travels.Add(newTravel);
context.SaveChanges();
return newTravel.GetViewModel;
}
public TravelViewModel? Update(TravelBindingModel model)
{
using var context = new TravelCompanyDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
var travel = context.Travels.FirstOrDefault(rec => rec.Id == model.Id);
if (travel == null)
{
return null;
}
travel.Update(model);
context.SaveChanges();
travel.UpdateConditions(context, model);
transaction.Commit();
return travel.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
}
}
public TravelViewModel? Delete(TravelBindingModel model)
{
using var context = new TravelCompanyDatabase();
var element = context.Travels
.Include(x => x.Conditions)
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Travels.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}