save an object with a bidirectional relationship i

2019-04-25 12:10发布

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.

3条回答
混吃等死
2楼-- · 2019-04-25 12:17

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楼-- · 2019-04-25 12:24

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

查看更多
一夜七次
4楼-- · 2019-04-25 12:35

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.

查看更多
登录 后发表回答