using MongoDB.Bson; using MongoDB.Driver; using SushiBarContracts.BindingModels; using SushiBarContracts.SearchModels; using SushiBarContracts.StoragesContracts; using SushiBarContracts.ViewModels; using SushiBarMongoDB.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SushiBarMongoDB.Implements { public class PlaceStorage : IPlaceStorage { public void ClearEntity() { using var context = new SushiBarMongoDB(); context.GetCollection("Places") .DeleteMany(Builders.Filter.Empty); } public PlaceViewModel? GetElement(PlaceSearchModel model) { if (!model.Id.HasValue) { return null; } using (var context = new SushiBarMongoDB()) { var places = context.GetCollection("Places"); var filterBuilder = Builders.Filter; var filter = filterBuilder.Empty; if (!model.Id.HasValue) { filter &= filterBuilder.Eq(x => x.Id, model.Id); } return places.Find(filter) .FirstOrDefault() ?.GetViewModel; } } public List GetFilteredList(PlaceSearchModel model) { if (!model.PlaceNumber.HasValue) { return new List(); } using var context = new SushiBarMongoDB(); var places = context.GetCollection("Places"); var filter = Builders.Filter.Eq(x => x.Id, model.Id); return places .Find(filter) .ToList() .Select(x => x.GetViewModel) .ToList(); } public List GetFullList() { using var context = new SushiBarMongoDB(); var places = context.GetCollection("Places"); return places.Find(Builders.Filter.Empty) .ToList() .Select(x => x.GetViewModel) .ToList(); } public PlaceViewModel? Insert(PlaceBindingModel model) { using var context = new SushiBarMongoDB(); var places = context.GetCollection("Places"); model.Id = (int)places.CountDocuments(FilterDefinition.Empty); var place = Place.Create(model); places.InsertOne(place); return place.GetViewModel; } public PlaceViewModel? Update(PlaceBindingModel model) { using var context = new SushiBarMongoDB(); var places = context.GetCollection("Places"); var filter = Builders.Filter.Eq(x => x.Id, model.Id); var place = places.Find(filter).FirstOrDefault(); if (place == null) { return null; } place.Update(model); places.ReplaceOne(filter, place); return place.GetViewModel; } public PlaceViewModel? Delete(PlaceBindingModel model) { using var context = new SushiBarMongoDB(); var places = context.GetCollection("Places"); var filter = Builders.Filter.Eq(x => x.Id, model.Id); var place = places.FindOneAndDelete(filter); return place?.GetViewModel; } } }