简体   繁体   English

MongoDB C#驱动程序:如何将对象列表序列化为对象ID列表?

[英]MongoDB c# driver: How to serialize a list of objects as a list of object ids?

It surprises me that i haven't found a simple answer to this question, so here it goes: 令我惊讶的是我还没有找到这个问题的简单答案,所以就这样:

Given an object model like this - 给定这样的对象模型-

public class Foo
{
    public string Id {get; set;}
    public List<Bar> Bars {get; set;}
}

public class Bar
{
    public string Id {get; set;}
    public string Name {get; set;}
}

How do I customize the mongodb c# driver to serialize a Foo instance to a document in the database that looks like this: 如何自定义mongodb c#驱动程序以将Foo实例序列化为数据库中的文档,如下所示:

{ "Id" : "XXXXX", "Bars" : [ { "Id" : "XXXXX" }, { "Id" : "XXXXX" } ] }

Foos and Bars will be stored in different collections. Foos和Bars将存储在不同的集合中。 So, I don't want to do something that will affect all Bars, because serializing a Bar to the Bar collection should keep all the properties of Bar. 因此,我不想做会影响所有Bar的事情,因为将Bar序列化为Bar集合应该保留Bar的所有属性。

I don't want any dependencies on the mongodb driver in my model classes. 我不想在模型类中对mongodb驱动程序有任何依赖性。

Maybe a better dupe candidate would have been MongoDB C# driver - serialization of POCO references? 也许更好的候选对象应该是MongoDB C#驱动程序-POCO引用的序列化?

Anyway, to provide an answer instead getting excited over possible dupes: No, it's not possible with the C# driver to do that. 无论如何,要提供答案而不是对可能的欺骗感到兴奋:不,使用C#驱动程序无法做到这一点。

The C# driver is relatively low-level and doesn't try to be an object-document-mapper. C#驱动程序是相对较低级别的,因此不会尝试成为对象文档映射器。 One could probably develop an ODM based on the C# driver, because it offers a number of hooks, but, as I have pointed out in a different answer, that is an extremely challenging and large task and the result, in my opinion, is always leaky. 可能可以开发基于C#驱动程序的ODM,因为它提供了许多钩子,但是,正如我在另一个答案中指出的那样,这是一项极富挑战性的艰巨任务,我认为结果总是漏水的。 Also, with the hooks you'd probably get a dependency on the C# driver in your code which you don't want. 同样,使用钩子,您可能会不需要代码而依赖C#驱动程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM