Save bidirectional object in mongodb using official c # driver

I have two classes:

public Class Company { public IList<Employee> Employees; } public Class Employee { public Company WorkPlace; } 

when I want to save an object of class Company:

 MongoDatabase Database = MongoServer.GetDatabase("db"); var workPlace = new Company(); var employee = new Employee { WorkPalce = workPlace} workPlace.Employees = new List<Employee>{ employee }; Database.GetCollection<Company>("company").Save(workPlace); 

A StackOverFlow exception will be thrown.

+7
source share
3 answers

This is because you have a loop formed by classes referencing each other, it is obvious that the driver is not equipped to handle this, and I'm not sure what it should.

You need to decide how you want this data to be modeled in the database.
If you have two collections, one of the companies and one of the employees, then at the data level you should just include an id for the links.

If you have only one collection of companies, then you just need to change the employee class to refer to the company with an identifier instead of an object reference.

This is only needed in the database, but you can expand your model in your C # code to automatically add a link to an object or lazy loading, etc. (avoiding the choice of N + 1 questions, how do you do it) depending on what is appropriate for the situation.

+6
source

This question was also asked in Google groups:

https://groups.google.com/group/mongodb-user/browse_thread/thread/4ea7c6885bfb4f33#

and there are some additional answers.

0
source

I suggest try kundera. He should be able to handle such a case for Mongo.

https://github.com/impetus-opensource/Kundera take a look at the kunder examples on git @ github.com: impulse-open source / Kundera-Examples.git

0
source

All Articles