LabSubd/Subd/MongoDB/StatusStorage.cs

89 lines
2.9 KiB
C#

using Contracts.BindingModels;
using Contracts.SearchModel;
using Contracts.Storage;
using Contracts.ViewModels;
using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Diagnostics.Metrics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MongoDB
{
public class StatusStorage : IStatusStorage
{
public MongoClient contex;
public StatusStorage()
{
contex = MongoDateBase.getInstance().client;
}
public StatusVM? Delete(StatusBM model)
{
IMongoDatabase db = contex.GetDatabase("logistic");
var collection = db.GetCollection<BsonDocument>("Status");
var res = collection.FindOneAndDelete(new BsonDocument("name", model.Title));
if (res == null)
return null;
return new StatusVM
{
Title = res["name"].ToString()
};
}
public StatusVM? GetElement(StatusSM model)
{
IMongoDatabase db = contex.GetDatabase("logistic");
var collection = db.GetCollection<BsonDocument>("Status");
BsonDocument status = collection.Find(new BsonDocument("name",model.Title)).FirstOrDefault();
if (status == null)
return null;
return new StatusVM
{
Title = status["name"].ToString()
};
}
public List<StatusVM> GetFullList()
{
IMongoDatabase db = contex.GetDatabase("logistic");
var collection = db.GetCollection<BsonDocument>("Status");
List<BsonDocument> statuses = collection.Find(new BsonDocument()).ToList();
List < StatusVM > res = new List<StatusVM>();
foreach (var status in statuses)
{
res.Add(new StatusVM
{
Title = status["name"].ToString()
}) ;
}
return res;
}
public StatusVM? Insert(StatusBM model)
{
IMongoDatabase db = contex.GetDatabase("logistic");
var collection = db.GetCollection<BsonDocument>("Status");
BsonDocument status = new BsonDocument { { "name", model.Title } };
collection.InsertOne(status);
return new StatusVM { Title = model.Title };
}
public StatusVM? Update(StatusBM model)
{
IMongoDatabase db = contex.GetDatabase("logistic");
var collection = db.GetCollection<BsonDocument>("Status");
var result = collection.UpdateOneAsync(new BsonDocument("name", model.oldTitle), new BsonDocument("$set", new BsonDocument("name", model.Title)));
if(result == null)
return null;
return new StatusVM
{
Title = model.Title
};
}
}
}