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 RouteStorage : IRouteStorage { public List GetFullList() { using var context = new LogisticContext(); return context.Routes.FromSqlRaw("Select * From Route").Include(u => u.PlaceStartNavigation).Include(a => a.PlaceEndNavigation) .ToList() .Select(x => x.GetViewModel) .ToList(); } public List GetFilteredList(RouteSM model) { if (!model.Length.HasValue && !model.Start.HasValue && !model.End.HasValue) { return new(); } using var context = new LogisticContext(); if(model.Length.HasValue) return context.Routes .FromSqlRaw("Select * FROM Route WHERE Length <= {0}", model.Length).Include(u => u.PlaceStartNavigation).Include(a => a.PlaceEndNavigation) .ToList() .Select(x => x.GetViewModel) .ToList(); else if(model.Start.HasValue) return context.Routes .FromSqlRaw("Select * FROM Route WHERE PlaceStart = {0} ", model.Start).Include(u => u.PlaceStartNavigation).Include(a => a.PlaceEndNavigation) .ToList() .Select(x => x.GetViewModel) .ToList(); return context.Routes .FromSqlRaw("Select * FROM Route WHERE PlaceEnd = {0} ", model.End).Include(u => u.PlaceStartNavigation).Include(a => a.PlaceEndNavigation) .ToList() .Select(x => x.GetViewModel) .ToList(); } public RouteVM? GetElement(RouteSM model) { if (!model.Id.HasValue && !model.Start.HasValue && !model.End.HasValue) { return null; } using var context = new LogisticContext(); var mid = context.Routes.FromSqlRaw("Select * from Route r where r.id = {0}", model.Id).Include(u => u.PlaceStartNavigation).Include(a => a.PlaceEndNavigation).ToList(); if (mid.Count == 0) return null; var res = mid[0]?.GetViewModel; return res; } public RouteVM? Insert(RouteBM model) { using var context = new LogisticContext(); var newRoute = Route.Create(context, model); if (newRoute == null) { return null; } context.Routes.Add(newRoute); context.SaveChanges(); return newRoute.GetViewModel; } public RouteVM? Update(RouteBM model) { using var context = new LogisticContext(); using var transaction = context.Database.BeginTransaction(); try { var route = context.Routes.FirstOrDefault(rec => rec.Id == model.Id); if (route == null) { return null; } route.Update(model); context.SaveChanges(); transaction.Commit(); return route.GetViewModel; } catch { transaction.Rollback(); throw; } } public RouteVM? Delete(RouteBM model) { using var context = new LogisticContext(); var element = context.Routes .FirstOrDefault(rec => rec.Id == model.Id); if (element != null) { context.Routes.Remove(element); context.SaveChanges(); return element.GetViewModel; } return null; } } }