LabSubd/Subd/MongoDB/CompanyStorage.cs

108 lines
3.8 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.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MongoDB
{
public class CompanyStorage : ICompanyStorage
{
public MongoClient contex;
public CompanyStorage()
{
contex = MongoDateBase.getInstance().client;
}
public CompanyVM? Delete(CompanyBM model)
{
IMongoDatabase db = contex.GetDatabase("logistic");
var collection = db.GetCollection<BsonDocument>("Company");
var res = collection.FindOneAndDelete(new BsonDocument("name", model.Title));
if (res == null)
return null;
return new CompanyVM
{
Title = res["name"].ToString(),
StatusTitle = res["Status"].ToString()
};
}
public CompanyVM? GetElement(CompanySM model)
{
IMongoDatabase db = contex.GetDatabase("logistic");
var collection = db.GetCollection<BsonDocument>("Company");
BsonDocument company = collection.Find(new BsonDocument("name", model.Title)).FirstOrDefault();
if (company == null)
return null;
return new CompanyVM
{
Title = company["name"].ToString(),
StatusTitle = company["Status"].ToString()
};
}
public List<CompanyVM> GetFilteredList(CompanySM model)
{
IMongoDatabase db = contex.GetDatabase("logistic");
var collection = db.GetCollection<BsonDocument>("Company");
List<BsonDocument> statuses = collection.Find(new BsonDocument { { "$regex",$"^.{model.Title}.$"} }).ToList();
List<CompanyVM> res = new List<CompanyVM>();
foreach (var status in statuses)
{
res.Add(new CompanyVM
{
Title = status["name"].ToString(),
StatusTitle = status["Status"].ToString()
});
}
return res;
}
public List<CompanyVM> GetFullList()
{
IMongoDatabase db = contex.GetDatabase("logistic");
var collection = db.GetCollection<BsonDocument>("Company");
List<BsonDocument> statuses = collection.Find(new BsonDocument()).ToList();
List<CompanyVM> res = new List<CompanyVM>();
foreach (var status in statuses)
{
res.Add(new CompanyVM
{
Title = status["name"].ToString(),
StatusTitle = status["Status"].ToString()
});
}
return res;
}
public CompanyVM? Insert(CompanyBM model)
{
IMongoDatabase db = contex.GetDatabase("logistic");
var collection = db.GetCollection<BsonDocument>("Company");
BsonDocument status = new BsonDocument { { "name", model.Title },{"Status", model.StatusTitle } };
collection.InsertOne(status);
return new CompanyVM { Title = model.Title, StatusTitle = model.StatusTitle };
}
public CompanyVM? Update(CompanyBM model)
{
IMongoDatabase db = contex.GetDatabase("logistic");
var collection = db.GetCollection<BsonDocument>("Company");
var result = collection.UpdateOneAsync(new BsonDocument("name", model.oldTitle), new BsonDocument("$set", new BsonDocument("name", model.Title)));
if (result == null)
return null;
return new CompanyVM
{
Title = model.Title,
StatusTitle = model.StatusTitle,
};
}
}
}