Created
April 22, 2013 20:26
-
-
Save beyond-code-github/5438233 to your computer and use it in GitHub Desktop.
Implementation of BsonDocumentBackedClass serializer, with id generation and concrete property
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using MongoDB.Bson; | |
using MongoDB.Bson.Serialization; | |
using MongoDB.Bson.Serialization.IdGenerators; | |
using MongoDB.Bson.Serialization.Serializers; | |
public class MongoDocumentClassSerializer : BsonDocumentBackedClassSerializer<MongoDocument>, IBsonIdProvider | |
{ | |
public MongoDocumentClassSerializer() | |
{ | |
this.RegisterMember("Id", "_id", ObjectIdSerializer.Instance, typeof(ObjectId), null); | |
} | |
protected override MongoDocument CreateInstance(BsonDocument backingDocument) | |
{ | |
return new MongoDocument(backingDocument, this); | |
} | |
public bool GetDocumentId(object document, out object id, out Type idNominalType, out IIdGenerator idGenerator) | |
{ | |
idNominalType = typeof(ObjectId); | |
idGenerator = ObjectIdGenerator.Instance; | |
var mongoDocument = document as MongoDocument; | |
if (mongoDocument == null) | |
{ | |
id = null; | |
return false; | |
} | |
id = mongoDocument.Id; | |
return true; | |
} | |
public void SetDocumentId(object document, object id) | |
{ | |
var mongoDocument = document as MongoDocument; | |
if (mongoDocument != null) | |
{ | |
mongoDocument.Id = (ObjectId)id; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment