using MongoDB.Driver;
using MongoDbGenericRepository.Models;
namespace MongoDbGenericRepository
{
///
/// The MongoDb context
///
public class MongoDbContext : IMongoDbContext
{
private readonly IMongoClient _client;
private readonly IMongoDatabase _database;
static MongoDbContext()
{
// Avoid legacy UUID representation: use Binary 0x04 subtype.
MongoDefaults.GuidRepresentation = MongoDB.Bson.GuidRepresentation.Standard;
}
public MongoDbContext(string connectionString, string databaseName)
{
_client = new MongoClient(connectionString);
_database = _client.GetDatabase(databaseName);
}
///
/// The private GetCollection method
///
///
///
public IMongoCollection GetCollection()
{
return _database.GetCollection(Pluralize());
}
///
/// Returns a collection for a document type that has a partition key.
///
///
/// The value of the partition key.
public IMongoCollection GetCollection(string partitionKey) where TDocument : IDocument
{
return _database.GetCollection(partitionKey +"-"+ Pluralize());
}
///
/// Drops a collection, use very carefully.
///
///
public void DropCollection()
{
_database.DropCollection(Pluralize());
}
///
/// Drops a collection having a partitionkey, use very carefully.
///
///
public void DropCollection(string partitionKey)
{
_database.DropCollection(partitionKey + "-" + Pluralize());
}
///
/// Very naively pluralizes a TDocument type name.
///
///
///
private string Pluralize()
{
return typeof(TDocument).Name.ToLower() + "s";
}
}
}