Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should c# mongodb documents inherit from BsonDocument

Should mongodb document classes written in c# inherit from BsonDocument?

For example:

/// <summary>
/// Company document
/// </summary>
public class CompanyDocument : BsonDocument
{
    /// <summary>
    /// Collection name
    /// </summary>
    public const string COLLECTION_NAME = "company";

    /// <summary>
    /// Unique company name
    /// </summary>
    [BsonElement("name")]
    public string Name
    {
        get;
        set;
    }

    /// <summary>
    /// List of referenced users
    /// </summary>
    [BsonElement("users")]
    public IList<MongoDBRef> Users
    {
        get;
        set;
    }
}

Because when i want to query data, it seems that I need to inherit from BsonDocument. Or should it be more like a POCO object or inherit from some thing else?

Thank you very much!

like image 335
BendEg Avatar asked Oct 27 '25 03:10

BendEg


1 Answers

I know this is an old question, but in case someone stumbles here looking for an answer like I did. The answer is NO.

While it is possible, it has been noted to cause many problems. The one I saw specifically was with serialization.

I ran across these two bug reports:

  • https://jira.mongodb.org/browse/CSHARP-1380
  • https://jira.mongodb.org/browse/CSHARP-1578

A few excerpts from them that explain it better than I can:

If you really want to subclass BsonDocument what you will need to do is wire things up so that your MyBsonDocument values get serialized correctly. -- Robert Stam


BsonDocument can represent any structure that exists. So, the only reason to inherit is (a) to provide a different behavior (RawBsonDocument, LazyBsonDocument), or (b) to provide strongly-typed access to certain fields. -- Craig Wilson

like image 60
Jerren Saunders Avatar answered Oct 29 '25 17:10

Jerren Saunders



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!