PIbd-23_Minhasapov_R.H._Aut.../AutomobilePlant/AutomobilePlantDatabaseImplement/Implements/CarStorage.cs

131 lines
4.1 KiB
C#
Raw Normal View History

using AutomobilePlantContracts.StorageContracts;
using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.SearchModels;
using AutomobilePlantContracts.ViewModels;
using AutomobilePlantDatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace AutomobilePlantDatabaseImplement.Implements
{
public class CarStorage : ICarStorage
{
public CarViewModel? GetElement(CarSearchModel model)
{
if (string.IsNullOrEmpty(model.CarName) && !model.Id.HasValue)
{
return null;
}
using var context = new AutomobilePlantDatabase();
return context.Cars.Include(x => x.Components)
.ThenInclude(x => x.Component)
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.CarName) &&
x.CarName == model.CarName) ||
(model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public List<CarViewModel> GetFilteredList(CarSearchModel model)
{
if (string.IsNullOrEmpty(model.CarName))
{
return new();
}
using var context = new AutomobilePlantDatabase();
return context.Cars
.Include(x => x.Components)
.ThenInclude(x => x.Component)
.Where(x => x.CarName.Contains(model.CarName))
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public List<CarViewModel> GetFullList()
{
using var context = new AutomobilePlantDatabase();
return context.Cars
.Include(x => x.Components)
.ThenInclude(x => x.Component)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public CarViewModel? Insert(CarBindingModel model)
{
using var context = new AutomobilePlantDatabase();
using var transaction = context.Database.BeginTransaction();
{
try
{
var newCar = Car.Create(context, model);
if (newCar == null)
{
transaction.Rollback();
return null;
}
context.Cars.Add(newCar);
context.SaveChanges();
context.Database.CommitTransaction();
return newCar.GetViewModel;
}
catch (Exception)
{
transaction.Rollback();
return null;
}
}
}
public CarViewModel? Update(CarBindingModel model)
{
using var context = new AutomobilePlantDatabase();
using var transaction = context.Database.BeginTransaction();
{
try
{
var car = context.Cars.FirstOrDefault(x => x.Id == model.Id);
if (car == null)
{
transaction.Rollback();
return null;
}
car.Update(model);
2023-04-09 21:23:18 +04:00
car.UpdateComponents(context, model);
context.SaveChanges();
context.Database.CommitTransaction();
return car.GetViewModel;
}
catch (Exception)
{
transaction.Rollback();
return null;
}
}
}
public CarViewModel? Delete(CarBindingModel model)
{
using var context = new AutomobilePlantDatabase();
var element = context.Cars.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Cars.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}