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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With