简体   繁体   中英

Adding serialization information for MongoDB custom serializer

I have a class defined as follows:

class Person
{
  public String Id { get; set; }
  public String Name { get; set; }
  public Person Mother { get; set; }
}

I've implemented a custom serializer for the Mother property to serialize the Id only. The final BSON would look something like this:

[{
   "_id": "54df1095fa0bd7122cb2c550", 
   "name": "John", 
   "mother": { "_id": "54df1095fa0bd7122cb2c551" }
}]

If I try to execute a query to find a person with a given mother as follows:

var results = await collection.Find<Person> (p => p.Mother.Id == "...").ToListAsync ();

The driver complains with the following:

{"Unable to determine the serialization information for the expression: p.Mother.Id."}

Is there a way to add serialization info to the driver so it knows to call my custom serializer to deserialize Person for this type of query?

Yes, there are two interfaces you may implement to provide serialization information. IBsonDocumentSerializer and IBsonArraySerializer . In this case, you'll want to implement IBsonDocumentSerializer on your customer serializer and handle the GetMemberSerializationInfo call for the memberName Id .

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