8

I have two class like this:

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);

StackOverFlow Exception will be thrown.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Omid.Hanjani
  • 1,444
  • 2
  • 20
  • 29

3 Answers3

9

This is being caused because you have a cycle formed by the classes referencing each other, clearly the driver is not equipped to handle this and I am not convinced it should.

You need to decide how you want this data modelled in the database.
If you are having two collections, one of companies and one of employees, then at a data level you should be just including id's for the references.

If you are just having a single collection of companies though, then you just need to change the employee class to reference back to the company with an id instead of an object reference.

This only needs to happen in the database though, you can extend your model in your c# code to automatically add the object reference or lazy load it etc (avoiding select N+1 issues as you do) depending on what is right for the situation.

Chris Sainty
  • 9,086
  • 1
  • 26
  • 31
  • if i change the employee class to reference back to the company with an id instead of an object reference, so when i have a list of Employee and iterate the list and want to use Company of each Employee, for each one a query will be generated. this will be slow, don't be? – Omid.Hanjani Dec 11 '11 at 07:58
  • 1
    @OmidRH: Yes, that will typically be comparatively slow. There are many strategies to mitigate, but it depends on what you exactly you want to achieve. For example, if you need to display the company name for each employee, you might want to copy the company name to the employee. Displaying a list of employees and their company names is easy then, but when the company name changes, you'll have to update all employees. This is called de-normalization. In NoSql, the queries you need to support shape the data structure, not the data you need to store. – mnemosyn Dec 11 '11 at 10:45
0

This question was also asked on Google groups:

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

and there are some additional answers there.

Robert Stam
  • 12,039
  • 2
  • 39
  • 36
0

I suggest, try kundera. It should be able to handle such case for Mongo.

https://github.com/impetus-opensource/Kundera take a look at kundera-examples at git@github.com:impetus-opensource/Kundera-Examples.git

vivek mishra
  • 161
  • 1
  • 3