简体   繁体   中英

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:

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

Foos and Bars will be stored in different collections. 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.

I don't want any dependencies on the mongodb driver in my model classes.

Maybe a better dupe candidate would have been MongoDB C# driver - serialization of POCO references?

Anyway, to provide an answer instead getting excited over possible dupes: No, it's not possible with the C# driver to do that.

The C# driver is relatively low-level and doesn't try to be an object-document-mapper. 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. Also, with the hooks you'd probably get a dependency on the C# driver in your code which you don't want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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