If you’ve Mongo you’ve discovered that communicating with MongoDB via Documents is painful. We care about storing our domain objects and having powerful ways of fetching them again from the data store. How do we accomplish those tasks when then tool doesn’t offer those options?
The answer is, of course, we extend the tool so that we can express our intent in the most natural language we can. To me this means Linq or some reasonable subset thereof.
So lets start with the domain object Person:
mongodb
[Serializable]
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
The object is marked Serializable but is otherwise unremarkable. If I have an instance of person I’d like to be able to simply pass it to a Save method on the collection as follows.
var person = new Person
{
FirstName = "Loreena",
LastName = "McKennitt"
};
_people.Save(person);
We can’t change the IMongoCollection object directly but we can use an extension method to build the interface we’re looking for:
public static class IMongoCollectionExtensions
{
public static void Save<T>(this IMongoCollection collection, T item) where T: class
{
// magic happens
}
}
I know there is some support for FluentMongo, but is this possible?