SUBD_SushiBar/SushiBar/SushiBarMongoDB/Implements/BuyerStorage.cs

111 lines
3.6 KiB
C#

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 BuyerStorage : IBuyerStorage
{
public void ClearEntity()
{
using var context = new SushiBarMongoDB();
context.GetCollection<Buyer>("Buyers")
.DeleteMany(Builders<Buyer>.Filter.Empty);
}
public List<BuyerViewModel> GetFullList()
{
using var context = new SushiBarMongoDB();
var buyers = context.GetCollection<Buyer>("Buyers");
return buyers.Find(Builders<Buyer>.Filter.Empty)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public List<BuyerViewModel> GetFilteredList(BuyerSearchModel model)
{
if(string.IsNullOrEmpty(model.BuyerName)) return new List<BuyerViewModel>();
using var context = new SushiBarMongoDB();
var buyers = context.GetCollection<Buyer>("Buyers");
var filterBuilder = Builders<Buyer>.Filter;
var filter = filterBuilder.Regex(x => x.BuyerName, new BsonRegularExpression(model.BuyerName));
return buyers
.Find(filter)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public BuyerViewModel? GetElement(BuyerSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using (var context = new SushiBarMongoDB())
{
var buyers = context.GetCollection<Buyer>("Buyers");
var filterBuilder = Builders<Buyer>.Filter;
var filter = filterBuilder.Empty;
if (!model.Id.HasValue)
{
filter &= filterBuilder.Eq(x => x.Id, model.Id);
}
return buyers.Find(filter)
.FirstOrDefault()
?.GetViewModel;
}
}
public BuyerViewModel? Insert(BuyerBindingModel model)
{
using var context = new SushiBarMongoDB();
var buyers = context.GetCollection<Buyer>("Buyers");
model.Id = (int)buyers.CountDocuments(FilterDefinition<Buyer>.Empty)+1;
var buyer = Buyer.Create(model);
buyers.InsertOne(buyer);
return buyer.GetViewModel;
}
public BuyerViewModel? Update(BuyerBindingModel model)
{
using var context = new SushiBarMongoDB();
var buyers = context.GetCollection<Buyer>("Buyers");
var filter = Builders<Buyer>.Filter.Eq(x => x.Id, model.Id);
var buyer = buyers.Find(filter).FirstOrDefault();
if (buyer == null)
{
return null;
}
buyer.Update(model);
buyers.ReplaceOne(filter, buyer);
return buyer.GetViewModel;
}
public BuyerViewModel? Delete(BuyerBindingModel model)
{
using var context = new SushiBarMongoDB();
var categories = context.GetCollection<Buyer>("Buyers");
var filter = Builders<Buyer>.Filter.Eq(x => x.Id, model.Id);
var category = categories.FindOneAndDelete(filter);
return category?.GetViewModel;
}
}
}