Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo DB C# serializer - circular reference

Tags:

c#

mongodb

I have a complex model I want to persist to Mongo DB. This model has some circular reference I don't want to break.

Apparently I can't do that with the official Mongo C# driver. Json.Net can serialize properly in Bson, and handle my model without any problem.

Can I change the mongo driver serializer ? Or do you have any other suggestion to handle this case (other than just avoid circular reference or ignore property) ?

Thank you.

like image 693
Persi Avatar asked Sep 13 '25 11:09

Persi


1 Answers

Customized serialization/deserialization is a good solution, but it does not have to be painful. The simplest way may be for your model to use the ISupportInitialize interface, and implement the BeginInit() and EndInit() methods.

Sergio Costa has a good example of using this interface to deal with circular references on a web page titled Serializing circular references in MongoDb.

like image 154
Karl Wenzel Avatar answered Sep 16 '25 02:09

Karl Wenzel