Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB C# driver - serialization of POCO references?

I'm researching MongoDB at the moment. It's my understanding that the official C# driver can perform serialization and deserialization of POCOs. What I haven't found information on yet is how a reference between two objects is serialized. [I'm talking about something that would be represented as two seperate documents, with ID links, rather than embeded documents.

Can the serialization mechanism handle this kind of situation? (1):

class Thing {
    Guid Id {get; set;}
    string Name {get; set;}
    Thing RelatedThing {get; set;}
}

Or do we have to sacrifice some OOP, and do something like this? (2) :

class Thing {
    Guid Id {get; set;}
    string Name {get; set;}
    Guid RelatedThing_ID {get; set;}
}

UPDATE:

Just a couple of related questions then...

a) If the serializer is able to handle situation (1). What is an example of how to do this without using embedding?

b) If using embedding, would it be possible to query across all 'Things' regardless of whether they were 'parents' or embedded elements? How would such a query look like?

like image 848
UpTheCreek Avatar asked Jul 01 '11 22:07

UpTheCreek


People also ask

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.

What is a MongoDB driver?

The official MongoDB Node. js driver allows Node. js applications to connect to MongoDB and work with data. The driver features an asynchronous API which allows you to interact with MongoDB using Promises or via traditional callbacks.

Is MongoDB paid?

MongoDB allows teams to choose their cloud provider of choice while providing database management that streamlines every aspect of database administration. It's easy to get started with MongoDB Atlas, and it's free.


1 Answers

The C# driver can handle serializing the class containing a reference to another instance of itself (1). However:

  1. As you surmised, it will use embedding to represent this
  2. There must be no circular paths in the object graph or a stack overflow will occur

If you want to store it as separate documents you will have to use your second class (2) and do multiple inserts.

Querying across multiple levels is not really possible when the object is stored as one large document with nested embedding. You might want to look at some alternatives like:

https://docs.mongodb.com/manual/applications/data-models-tree-structures/

like image 118
Robert Stam Avatar answered Oct 13 '22 12:10

Robert Stam