问题
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.
回答1:
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.
回答2:
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.
回答3:
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
来源:https://stackoverflow.com/questions/8461996/save-an-object-with-a-bidirectional-relationship-in-mongodb-using-official-c-sha