using CarServiceContracts.BindingModels; using CarServiceContracts.SearchModels; using CarServiceContracts.StorageContracts; using CarServiceContracts.ViewModels; using CarServiceDatabase.Models; namespace CarServiceDatabase.Implements { public class VehicleStorage : IVehicleStorage { public List GetFullList() { using var context = new CarServiceDbContext(); return context.Vehicles .Select(x => x.GetViewModel) .ToList(); } public List GetFilteredList(VehicleSearchModel model) { using var context = new CarServiceDbContext(); return context.Vehicles .Where(x => x.Id == model.Id) .Select(x => x.GetViewModel) .ToList(); } public VehicleViewModel? GetElement(VehicleSearchModel model) { if (model == null) { return null; } using var context = new CarServiceDbContext(); if (model.Id.HasValue)//ищем по Id { return context.Vehicles.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; } return null; } public VehicleViewModel? Insert(VehicleBindingModel model) { using var context = new CarServiceDbContext(); var newVehicle = Vehicle.Create(context, model); if (newVehicle != null) { context.Vehicles.Add(newVehicle); context.SaveChanges(); return newVehicle.GetViewModel; } return null; } public VehicleViewModel? Update(VehicleBindingModel model) { using var context = new CarServiceDbContext(); var vehicle = context.Vehicles .FirstOrDefault(x => x.Id == model.Id); if (vehicle == null) { return null; } vehicle.Update(context, model); context.SaveChanges(); return vehicle.GetViewModel; } public VehicleViewModel? Delete(VehicleBindingModel model) { using var context = new CarServiceDbContext(); var vehicle = context.Vehicles .FirstOrDefault(x => x.Id == model.Id); if (vehicle == null) { return null; } context.Vehicles.Remove(vehicle); context.SaveChanges(); return vehicle.GetViewModel; } } }