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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With