SUBD_SushiBar/SushiBar/SushiBarMongoDB/Implements/PlaceStorage.cs

116 lines
3.6 KiB
C#
Raw Normal View History

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<Place>("Places")
.DeleteMany(Builders<Place>.Filter.Empty);
}
public PlaceViewModel? GetElement(PlaceSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using (var context = new SushiBarMongoDB())
{
var places = context.GetCollection<Place>("Places");
var filterBuilder = Builders<Place>.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<PlaceViewModel> GetFilteredList(PlaceSearchModel model)
{
if (!model.PlaceNumber.HasValue)
{
return new List<PlaceViewModel>();
}
using var context = new SushiBarMongoDB();
var places = context.GetCollection<Place>("Places");
var filter = Builders<Place>.Filter.Eq(x => x.Id, model.Id);
return places
.Find(filter)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public List<PlaceViewModel> GetFullList()
{
using var context = new SushiBarMongoDB();
var places = context.GetCollection<Place>("Places");
return places.Find(Builders<Place>.Filter.Empty)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public PlaceViewModel? Insert(PlaceBindingModel model)
{
using var context = new SushiBarMongoDB();
var places = context.GetCollection<Place>("Places");
model.Id = (int)places.CountDocuments(FilterDefinition<Place>.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<Place>("Places");
var filter = Builders<Place>.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<Place>("Places");
var filter = Builders<Place>.Filter.Eq(x => x.Id, model.Id);
var place = places.FindOneAndDelete(filter);
return place?.GetViewModel;
}
}
}