Simple-MongoDb – Just added support for generating ObjectId’s

As I’m working on adding support for DbReferences I added support for dealing with ObjectId’s in your typed classes. You can still skip them if you want, and instead rely on the database for the generation.

Note! I’m working against the MongoDB v.1.2.4 and not 1.3.x. I tested it against the later and got some strange results in my tests, so for now (during the implementation of DbRef) I will use v.1.2.4 and after that I will get it to work against v.1.3.x

So some short code examples of the ObjectId. First the new static factory method: SimoObjectId.NewId(). It generates a ObjectId according to specs (http://www.mongodb.org/display/DOCS/Object+IDs)

[TestMethod]
public void Insert_TypedDocumentWithAssignedId_IsStored()
{
    var document = new PersonWithId { _id = SimoObjectId.NewId(), Name = "Daniel" };

    using (var session = new SimoSession(CreateConnection()))
    {
        session[DbName][PersonsCollectionName].Insert(document);
    }

    var numOfDocs = GetDocumentCount(new { _id = document._id }, Constants.Commands.PersonsFullCollectionName);
    Assert.AreEqual(1, numOfDocs);
}

[Serializable]
public class PersonWithId
    : Person
{
    public virtual SimoObjectId _id { get; set; }
}

If you don’t want to call SimoObjectId.NewId() each time and you don’t want to add this in the constructor, there’s a simple alternative: the SimoAutoObjectId.

[TestMethod]
public void Insert_TypedDocumentWithAutoAssignedId_IsStored()
{
    var document = new PersonWithAutoId { Name = "Daniel" };

    using (var session = new SimoSession(CreateConnection()))
    {
        session[DbName][PersonsCollectionName].Insert(document);
    }

    var numOfDocs = GetDocumentCount(new { _id = document._id }, Constants.Commands.PersonsFullCollectionName);
    Assert.AreEqual(1, numOfDocs);
}

[Serializable]
public class PersonWithAutoId
    : Person
{
    private SimoAutoObjectId _simoAutoObjectId = new SimoAutoObjectId();

    public virtual SimoObjectId _id
    {
        get { return _simoAutoObjectId; }
        set { _simoAutoObjectId = value; }
    }
}

Of, course you then can’t rely on auto.properties anymore.

That’s it. The next time I hope I will wright about DbRef-support.

The source code as well as ZIP is available at: http://code.google.com/p/simple-mongodb/

//Daniel

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s