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 PlaceStorage : IPlaceStorage { public List GetFullList() { using var context = new LogisticContext(); return context.Places.FromSqlRaw("Select * From Place") .ToList() .Select(x => x.GetViewModel) .ToList(); } public List GetFilteredList(PlaceSM model) { if (string.IsNullOrEmpty(model.Title)) { return new(); } using var context = new LogisticContext(); return context.Places .FromSqlRaw("Select * FROM Place WHERE LIKE %{0}%", model.Title) .ToList() .Select(x => x.GetViewModel) .ToList(); } public PlaceVM? GetElement(PlaceSM model) { if (!model.Id.HasValue) { return null; } using var context = new LogisticContext(); return context.Places .FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id)) ?.GetViewModel; } public PlaceVM? Insert(PlaceBM model) { using var context = new LogisticContext(); var newPlace = Place.Create(context, model); if (newPlace == null) { return null; } context.Places.Add(newPlace); context.SaveChanges(); return newPlace.GetViewModel; } public PlaceVM? Update(PlaceBM model) { using var context = new LogisticContext(); using var transaction = context.Database.BeginTransaction(); try { var place = context.Places.FirstOrDefault(rec => rec.Id == model.Id); if (place == null) { return null; } place.Update(model); context.SaveChanges(); transaction.Commit(); return place.GetViewModel; } catch { transaction.Rollback(); throw; } } public PlaceVM? Delete(PlaceBM model) { using var context = new LogisticContext(); var element = context.Places .FirstOrDefault(rec => rec.Id == model.Id); if (element != null) { context.Places.Remove(element); context.SaveChanges(); return element.GetViewModel; } return null; } } }