121 lines
2.5 KiB
C#
121 lines
2.5 KiB
C#
using ForumContracts.BindingModels;
|
|
using ForumContracts.SearchModels;
|
|
using ForumContracts.StorageContracts;
|
|
using ForumContracts.ViewModels;
|
|
using ForumDatabaseImplement.Models;
|
|
using MongoDB.Bson;
|
|
using MongoDB.Driver;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace ForumMongoDataBase.Implements
|
|
{
|
|
public class AnswerStorage : IAnswerStorage
|
|
{
|
|
private readonly IMongoCollection<Answer> _collection;
|
|
public MongoClient context;
|
|
|
|
public AnswerStorage()
|
|
{
|
|
context = ForumMongoDataBase.getInstance().client;
|
|
_collection = context.GetDatabase("forum").GetCollection<Answer>("answers");
|
|
}
|
|
|
|
public AnswerViewModel? Delete(AnswerBindingModel model)
|
|
{
|
|
var filter = Builders<Answer>.Filter.Eq(a => a.Id, model.Id);
|
|
var answer = _collection.FindOneAndDelete(filter);
|
|
|
|
if (answer == null)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
return answer.GetViewModel();
|
|
}
|
|
|
|
public AnswerViewModel? GetElement(AnswerSearchModel model)
|
|
{
|
|
if (!model.Id.HasValue)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
var answer = _collection.Find(a => a.Id == model.Id.Value)
|
|
.FirstOrDefault();
|
|
|
|
if (answer == null)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
return answer.GetViewModel();
|
|
}
|
|
|
|
public List<AnswerViewModel> GetFilteredList(AnswerSearchModel model)
|
|
{
|
|
var filter = Builders<Answer>.Filter.Empty;
|
|
|
|
if (model.Id.HasValue)
|
|
{
|
|
filter &= Builders<Answer>.Filter.Eq(a => a.Id, model.Id.Value);
|
|
}
|
|
|
|
if (model.QuestionId.HasValue)
|
|
{
|
|
filter &= Builders<Answer>.Filter.Eq(a => a.QuestionId, model.QuestionId.Value);
|
|
}
|
|
else
|
|
{
|
|
return new List<AnswerViewModel>();
|
|
}
|
|
|
|
var answers = _collection.Find(filter)
|
|
.ToList()
|
|
.Select(a => a.GetViewModel())
|
|
.ToList();
|
|
|
|
return answers;
|
|
}
|
|
|
|
public List<AnswerViewModel> GetFullList()
|
|
{
|
|
var answers = _collection.Find(_ => true)
|
|
.ToList()
|
|
.Select(a => a.GetViewModel())
|
|
.ToList();
|
|
|
|
return answers;
|
|
}
|
|
|
|
public AnswerViewModel? Insert(AnswerBindingModel model)
|
|
{
|
|
var answer = Answer.Create(model);
|
|
|
|
if (answer == null)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
_collection.InsertOne(answer);
|
|
|
|
return answer.GetViewModel();
|
|
}
|
|
|
|
public AnswerViewModel? Update(AnswerBindingModel model)
|
|
{
|
|
var filter = Builders<Answer>.Filter.Eq(a => a.Id, model.Id);
|
|
var answer = _collection.Find(filter).FirstOrDefault();
|
|
|
|
answer.Update(model);
|
|
_collection.ReplaceOne(filter, answer);
|
|
|
|
return answer.GetViewModel();
|
|
}
|
|
}
|
|
}
|
|
|