title: MongoDB C# Driver Generic Types
body: <p>I'm trying to add generic objects to mongodb</p>
  <p>how can I have some thing like this works?</p>
  <p>if I must implement my own serializer, may you give me some hints, where can I start?</p>
  <pre><code>public class  ParameterBase{}
  [BsonDiscriminator(RootClass = true, Required = true)]
  [BsonKnownTypes(typeof(NumericParameter))]
  public class Parameter&lt;T&gt; : ParameterBase
  {
      [BsonId]
      [BsonRepresentation(BsonType.ObjectId)]
      public ObjectId Id { get; set; }
      public string Name{get;set;}
  
      public virtual Type Type { get{return typeof(T); } }      
      public virtual T Value
      {
          get { return _value; }
          set
          {
              if (EqualityComparer&lt;T&gt;.Default.Equals(_value, value) == false)
              {
                  _value = value;
              }
          }
      }
      protected T _value;       
  }
  
  public class NumericParameter : Parameter&lt;double&gt;
  {
      private double _value;
      public double Value{get{return _value;}set{_value = value;}}
  }
  
  public class StringParameter : Parameter&lt;string&gt;
  {
      private string _value;
      public string Value{get{return _value;}set{_value = value;}}
  }
  </code></pre>
  <p>the problem is
  when I try to add NumericParameter like this</p>
  <pre><code>var context = new DatabaseContext(&quot;test&quot;);
          var collection = context.db.GetCollection&lt;ParameterBase&gt;(&quot;RecipeParameterSet&quot;);
          var nParameter = new NumericParameter()
          {
              Name = &quot;Offset&quot;,
              Value = 1.8
          };
          collection.InsertOne(nParameter);
          Console.ReadLine();
  </code></pre>
  <p>this Code insert this document in the database</p>
  <pre class="lang-json prettyprint-override"><code>{
  &quot;_id&quot;:{&quot;$oid&quot;:&quot;000000000000000000000000&quot;},
  &quot;_t&quot;:[&quot;Parameter`1&quot;,&quot;NumericParameter&quot;],
  &quot;Name&quot;:&quot;Offset&quot;,
  &quot;Value&quot;:1.8
  }
  </code></pre>
  <p>and if I add the class StringParameter to the BsonKnownTypes of the class
  Parameter
  like this
  [BsonKnownTypes(typeof(NumericParameter), typeof(StringParameter))]</p>
  <p>I get this error</p>
  <blockquote>
  <p>System.ArgumentNullException: 'Class Ha.MongoDb.Playground.StringParameter cannot be assigned to Class Ha.MongoDb.Playground.Parameter`1[[System.Double, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].  Ensure that known types are derived from the mapped class.
  Parametername: type'</p>
  </blockquote>