RockyMountainHigh
RockyMountainHigh

Reputation: 3021

Creating generic MongoDb helper class in C# 4.0

I am trying to create a helper class for interacting with MongoDb in C# 4.0. I've been reading some of the documentation on serializing to Bson, etc. but am a little lost. What I have is a generic MongoHelper class with and Add(T objectToAdd), Delete(T objectToDelete) and Update(T objectToUpdate) method. The constructor takes in the server, db and collection info.

I am having trouble however, trying to serialize from T. I ignorantly tried something like this:

BsonClassMap.RegisterClassMap().ToBsonDocument();

I'm really lost on such a simple thing. Please help!

Upvotes: 1

Views: 2194

Answers (1)

Robert Stam
Robert Stam

Reputation: 12187

You don't have to serialize your objects. The driver does that for you. If you are working with C# classes just make sure your class has a public no-argument constructor and that the values you want serialized are exposed as public properties. Classes like that are handled automatically. Alternatively, you might choose to work at a lower level with BsonDocuments, but they also are serialized for you automatically.

All you need to do to save an object of class C to the database is:

var server = MongoServer.Create("mongodb://localhost/?safe=true");
var database = server.GetDatabase("test");
var collection = database.GetCollection<C>("test");
var c = new C();
// initialize c
collection.Insert(c);

That's all there is to it. To read it back you just write:

c = collection.FindOne();

although typically you would write a query as well.

Upvotes: 3

Related Questions