LabSubd/Subd/DataBase/Implements/CarStorage.cs

113 lines
3.3 KiB
C#
Raw Normal View History

using Contracts.BindingModels;
using Contracts.SearchModel;
using Contracts.Storage;
using Contracts.ViewModels;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataBase.Implements
{
public class CarStorage : ICarStorage
{
public List<CarVM> GetFullList()
{
using var context = new LogisticContext();
2023-05-05 21:47:09 +04:00
return context.Cars.FromSqlRaw("Select * from Car")
.Include(u => u.Status)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
2023-05-05 21:47:09 +04:00
}
public List<CarVM> GetFilteredList(CarSM model)
{
if (!model.StatusId.HasValue && !model.Tonnage.HasValue)
{
return new();
}
using var context = new LogisticContext();
if(model.StatusId.HasValue)
return context.Cars
2023-05-05 21:47:09 +04:00
.FromSqlRaw("Select * FROM Car WHERE status_id = {0}", model.StatusId)
.Include(u => u.Status)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
else
return context.Cars
.FromSqlRaw("Select * FROM Car WHERE Tonnage >= {0}", model.Tonnage)
2023-05-05 21:47:09 +04:00
.Include(u => u.Status)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public CarVM? GetElement(CarSM model)
{
if ( !model.Id.HasValue)
{
return null;
}
using var context = new LogisticContext();
return context.Cars
.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public CarVM? Insert(CarBM model)
{
using var context = new LogisticContext();
var newCar = Car.Create(context, model);
if (newCar == null)
{
return null;
}
context.Cars.Add(newCar);
context.SaveChanges();
return newCar.GetViewModel;
}
public CarVM? Update(CarBM model)
{
using var context = new LogisticContext();
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();
transaction.Commit();
return car.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
}
}
public CarVM? Delete(CarBM model)
{
using var context = new LogisticContext();
var element = context.Cars
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Cars.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}