using MongoDB.Driver; using SportCompetitionsContracts.BindingModels; using SportCompetitionsContracts.SearchModels; using SportCompetitionsContracts.StoragesContracts; using SportCompetitionsContracts.ViewModels; using SportCompetitionsMongo.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SportCompetitionsMongo.Implements { public class ResultStorage : IResultStorage { public void ClearEntity() { using var context = new SportCompetitionsMongoDB(); context.GetCollection("Results") .DeleteMany(Builders.Filter.Empty); } public List GetFullList() { using var context = new SportCompetitionsMongoDB(); var results = context.GetCollection("Results").Find(Builders.Filter.Empty).ToList(); return results.Select(x => x.GetViewModel).ToList(); } public List GetFilteredList(ResultSearchModel model) { using var context = new SportCompetitionsMongoDB(); if (!model.Id.HasValue) return new List(); var filterBuilder = Builders.Filter; var filter = filterBuilder.Empty; filter = filterBuilder.Eq("Id", model.Id); var results = context.GetCollection("Results").Find(filter).ToList(); return results.Select(x => x.GetViewModel).ToList(); } public ResultViewModel? GetElement(ResultSearchModel model) { using var context = new SportCompetitionsMongoDB(); var results = context.GetCollection("Results"); if (!model.Id.HasValue) return null; return results.Find(x => x.Id == model.Id).FirstOrDefault()?.GetViewModel; } public ResultViewModel? Insert(ResultBindingModel model) { using var context = new SportCompetitionsMongoDB(); var results = context.GetCollection("Results"); model.Id = (int)results.CountDocuments(FilterDefinition.Empty); var newResult = Result.Create(model); if (newResult == null) return null; results.InsertOne(newResult); return newResult.GetViewModel; } public ResultViewModel? Update(ResultBindingModel model) { using var context = new SportCompetitionsMongoDB(); var result = context.GetCollection("Results").Find(x => x.Id == model.Id).FirstOrDefault(); if (result == null) return null; result.Update(model); context.GetCollection("Results").ReplaceOne(x => x.Id == model.Id, result); return result.GetViewModel; } public ResultViewModel? Delete(ResultBindingModel model) { using var context = new SportCompetitionsMongoDB(); var element = context.GetCollection("Results").Find(x => x.Id == model.Id).FirstOrDefault(); if (element != null) { context.GetCollection("Results").DeleteOne(x => x.Id == model.Id); return element.GetViewModel; } return null; } } }