title: C# Serialization in MongoDb - _id on nested type, and some properties with private setters
body: <p>I'm in a position where I need to serialize some complex documents into MongoDb, but I can't change the class definition as I don't have control over the source.</p>
  
  <p>However, we need to ensure that callers can still use Linq, so we need to map the class correclty into MongoDb.</p>
  
  <p>Current there are few issues we're faced with:</p>
  
  <blockquote>
    <ol>
    <li>The <code>_id</code>_ representation is on a nested class.</li>
    <li>There are properties with private setters that need to be serialized/ deserialzied.</li>
    </ol>
  </blockquote>
  
  <p>The shape of the class looks a little like this:</p>
  
  <pre><code>public class AggregateType : AggregateBase
  {
      public int IntProperty { get; private set; }
  
      public ComplexObject ComplexObjectProperty { get; private set; }
  }
  </code></pre>
  
  <p>With <code>AggregateBase</code> looking like this:</p>
  
  <pre><code>abstract public class AggregateBase
  {
      public AggregateDetails Details { get; set; }
  }
  </code></pre>
  
  <p>And finally:</p>
  
  <pre><code>public class AggregateDetails
  {
      public Guid Id { get; set; }
  
      ...other properties
  }
  </code></pre>
  
  <p>On the base class <code>AggregateBase</code>, there is a property called <code>Details</code> which contains the <code>Id</code> of the aggregate, which is a <code>Guid</code>. This <code>Id</code> field needs to be mapped to the <code>ObjectId</code> or <code>_id</code> field within a MongoDb document.</p>
  
  <p>I need to be able to serialize the document, forcing the use of the <code>Details.Id</code> as the <code>_id</code>, and have the private setters serialized too.</p>
  
  <p>I've done this with CosmoDb using a custom <code>JsonContractResolver</code> without issue. But the move to MongoDb has proved a little more complex.</p>
  
  <p>It's worth noting that there are many <code>AggregateType</code> classes, all with a different shape. I'd like to find a generic way of serializing them, without having to write lots of specific mappers if possible - much like we do with CosmoDb.</p>
  
  <p>On top of that, we would need this solution to work with the Linq query provider for MongoDb too.</p>