PIbd-23_Starostin_I.K._Cour.../STODataBaseImplement/CarStorage.cs

110 lines
3.5 KiB
C#

using Microsoft.EntityFrameworkCore;
using STOContracts.BindingModels;
using STOContracts.SearchModels;
using STOContracts.StorageContracts;
using STOContracts.ViewModels;
using STODatabaseImplement;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DatabaseImplement
{
public class CarStorage : ICarStorage
{
public List<CarViewModel> GetFullList()
{
using var context = new STODatabase();
return context.Cars
.Include(x => x.TechnicalWorks)
.ThenInclude(x => x.TechnicalWork)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public List<CarViewModel> GetFilteredList(CarSearchModel model)
{
if (string.IsNullOrEmpty(model.CarNumber))
{
return new();
}
using var context = new STODatabase();
return context.Cars.Include(x => x.TechnicalWorks)
.ThenInclude(x => x.TechnicalWork)
.Where(x => x.CarNumber.Contains(model.CarNumber))
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public CarViewModel? GetElement(CarSearchModel model)
{
if (string.IsNullOrEmpty(model.CarNumber) &&
!model.Id.HasValue)
{
return null;
}
using var context = new STODatabase();
return context.Cars
.Include(x => x.TechnicalWorks)
.ThenInclude(x => x.TechnicalWork)
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.CarNumber) &&
x.CarNumber == model.CarNumber) ||
(model.Id.HasValue && x.Id ==
model.Id))
?.GetViewModel;
}
public CarViewModel? Insert(CarBindingModel model)
{
using var context = new STODatabase();
var newCar = Car.Create(context, model);
if (newCar == null)
{
return null;
}
context.Cars.Add(newCar);
context.SaveChanges();
return newCar.GetViewModel;
}
public CarViewModel? Update(CarBindingModel model)
{
using var context = new STODatabase();
using var transaction = context.Database.BeginTransaction();
try
{
var car = context.Cars.FirstOrDefault(rec =>
rec.Id == model.Id);
if (car == null)
{
return null;
}
car.Update(model);
context.SaveChanges();
car.UpdateTechnicalWorks(context, model);
transaction.Commit();
return car.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
}
}
public CarViewModel? Delete(CarBindingModel model)
{
using var context = new STODatabase();
var element = context.Cars
.Include(x => x.TechnicalWorks)
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Cars.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}