Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB C#: ID Serialization best pattern

Tags:

I have a class User and I need to work with them in web services.

Then problem is that if I try to serialize Id that is type of BsonObjectId, I see that have an empty property, that have an empty property, and so on ...

I have write this workaround in order, it's is a good solution?

public partial class i_User 
{
    [BsonId(IdGenerator = typeof(BsonObjectIdGenerator))]
    [NonSerialized]
    public BsonObjectId _id;

    public String Id
    {
        get
        {
            return this._id.ToString();
        }
    }   
}   

In this way, I can keep _Id as BsonObjectId but I send an string representation over the web in the property Id.

Another solution is to work with StringObjectIdGenerator

public partial class i_User 
{
    [BsonId(IdGenerator = typeof(StringObjectIdGenerator))]
    public String id;
}

But is see that MongoDB will store a string into database instead of ObjectId.

What is the best approach in order to work in a serialization environmental like web services and/or an client-server (Flash+C#)?

like image 449
Daniele Tassone Avatar asked Oct 08 '11 08:10

Daniele Tassone


People also ask

What is MongoDB C driver?

The MongoDB C Driver, also known as “libmongoc”, is a library for using MongoDB from C applications, and for writing MongoDB drivers in higher-level languages. It depends on libbson to generate and parse BSON documents, the native data format of MongoDB.

Can you use MongoDB with C#?

By developing with C# and MongoDB together one opens up a world of possibilities. Console, window, and web applications are all possible. As are cross-platform mobile applications using the Xamarin framework.

Is MongoDB free to use?

MongoDB is a NoSQL database that is open source. MongoDB is available in two editions. One is MongoDB Open Source, which is free as part of the Open-Source Community, but for the other editions, you must pay a License fee. When compared to the free edition, this edition has some advanced features.


1 Answers

If I understand you correctly, you want to access the Id property as a string, but have the Id saved as an ObjectId in MongoDB. This can be accomplished using BsonRepresentation with BsonId.

[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }

Details can be found here.

like image 70
Joe Waller Avatar answered Sep 17 '22 05:09

Joe Waller