Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDb's C# Drivers, is it possible to wrap it in a generic session?

I'm apologizing if I'm using the wrong terminology here. I'm still very much in the ORM world, but I've been playing around with MongoDb and really love what I see. One of the things I'm not liking is this:

var books = bookRepository.GetCollection<BsonDocument>("books");

And

foreach (var book in books.FindAllAs<Book>())
{
    Console.WriteLine("Author: {0}, Title: {1}", book.Author, book.Title);
}

I've found several tutorials on wrapping NoRM in a session but I can't figure out how to do it using the CSharp Drivers (the ones that Mongodb recommends / has on their github page).

What I'd really like to do is something like this for the first example:

var bookRepository = MongoRepository<Book>(); // probably should use IoC to resolve this

and

foreach (var book in books.FindAll())

Voila! I'm probably not the first person to want this, using strings everywhere seems a bit nutty, though I will grant that the tutorial is just an example. Is there a "best practices" example to setting this all up in such a manner?

Edit: Please let me know if this is crazy talk and not how to do things in Mongo, again this is my first test project.

like image 282
chum of chance Avatar asked Jun 26 '11 22:06

chum of chance


1 Answers

Here is snippet from my project:

public static MongoCollection<T> GetCollection<T>(string collectionName = null)
{
    if (string.IsNullOrWhiteSpace(collectionName))
    {
        Type g = typeof (T);
        collectionName = g.Name;
    }
    return MongoServer.Create(Config.MongoConnectionString).GetDatabase(Config.Database).GetCollection<T>(collectionName);
}

Now I dont need to specify a collection name as a string unless I want to override it:

var collection = GetCollection<MyEntity>();

or

var collection = GetCollection<MyEntity>("SomeOtherCOllection");

You can use some inflection utility\library to pluralize your collection names if you want.

Also, you dont need to specify the type in your Find methods if you specified the type when instantiating a collection class, like I have above.

For example, this is how I do it:

MongoCursor<MyEntity> results = collection.FindAll();

or

MongoCursor<MyEntity> results = collection.Find(query);
like image 152
Bryan Migliorisi Avatar answered Sep 28 '22 08:09

Bryan Migliorisi