93 lines
2.8 KiB
C#

using HotelContracts.BindingModels;
using HotelContracts.SearchModels;
using HotelContracts.StoragesContracts;
using HotelContracts.ViewModels;
using HotelDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HotelDatabaseImplement.Implements
{
public class BookingStorage : IBookingStorage
{
public BookingViewModel? Delete(BookingBindingModel model)
{
using var context = new HotelDatabase();
var element = context.Bookings.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
context.Bookings.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
public BookingViewModel? GetElement(BookingSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new HotelDatabase();
return context.Bookings.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
}
public List<BookingViewModel> GetFilteredList(BookingSearchModel model)
{
if (!model.Id.HasValue)
{
return new();
}
using var context = new HotelDatabase();
return context.Bookings.Where(x => x.Id == model.Id).Select(x => x.GetViewModel).ToList();
}
public List<BookingViewModel> GetFullList()
{
using var context = new HotelDatabase();
return context.Bookings.Select(x => x.GetViewModel).ToList();
}
public BookingViewModel? Insert(BookingBindingModel model)
{
var newBooking = Booking.Create(model);
if (newBooking == null)
{
return null;
}
using var context = new HotelDatabase();
context.Bookings.Add(newBooking);
context.SaveChanges();
return newBooking.GetViewModel;
}
public BookingViewModel? Update(BookingBindingModel model)
{
using var context = new HotelDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
var booking = context.Bookings.FirstOrDefault(x => x.Id == model.Id);
if (booking == null)
{
return null;
}
booking.Update(model);
context.SaveChanges();
transaction.Commit();
return booking.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
}
}
}
}