保存对象使用官方的C#驱动程序在MongoDB中一个双向关系 [英] save an object with a bidirectional relationship in mongodb using official c# driver

查看:211
本文介绍了保存对象使用官方的C#驱动程序在MongoDB中一个双向关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个类是这样的:

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.

您需要决定你想怎么这个数据库中的数据。结果
仿照如果您有两个集合,公司之一,雇员之一,然后在数据层面,你应该只包括ID对的引用。

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.

如果你是刚刚有公司的一个集合虽然,那么你只需要改变员工类的ID而不是对象引用来引用回公司。

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.

这仅需要在数据库中发生的,虽然,你可以在你的C#代码扩展你的模型自动添加对象引用或懒惰加载等(避免选择N +根据什么是正确的情况1的问题,你做的)。

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.

这篇关于保存对象使用官方的C#驱动程序在MongoDB中一个双向关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆