Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

save an object with a bidirectional relationship in mongodb using official c# driver

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.

like image 864
Omid-RH Avatar asked Dec 11 '11 04:12

Omid-RH


1 Answers

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.

like image 116
Chris Sainty Avatar answered Nov 04 '22 15:11

Chris Sainty