Set MongoDB to Serialize a class as BsonDocument












0















I have a Dictionary<string, object> as an insertion input for MongoDB.Save().



When I fill this dictionary with primitive types - the serialization process works fine but when I'm trying to insert my dictionary filled with some custom class (for example - Person class) I'm getting the next error:
.NET type 'Person' cannot be mapped to a BsonValue



I noticed that if I insert my custom type converted to BsonDocument the serialization process work great.



How can I define MongoDB to serialize a particular class as BsonDocument?





Update: real code provided



    here is my SensorData class: 

[DataContract]
public class SensorData
{

[DataMember]
[BsonElement]
[BsonRepresentation(BsonType.String)]
public string Type { get; set; }

[DataMember]
[BsonElement]
[BsonRepresentation(BsonType.String)]
public string Desc { get; set; }

[DataMember]
[BsonElement]
[BsonRepresentation(BsonType.String)]
public SensorStatus Status { get; set; }

[DataMember]
[BsonElement]
[BsonRepresentation(BsonType.String)]
public string Value { get; set; }

[DataMember]
[BsonElement]
[BsonRepresentation(BsonType.String)]
public string ValueUnits { get; set; }

[DataMember]
[BsonElement]
[BsonRepresentation(BsonType.Boolean)]
public bool Event { get; set; }

[DataMember]
[BsonElement]
[BsonRepresentation(BsonType.Int32)]
public int TTL { get; set; }
}


Here is the methods which saves the data to MongoDB:



public void Save(Dictionary<string, object> RawSensorMessageDictionary)
{
try
{
var policyColl = new MongoClient(ConnString).GetServer().GetDatabase(DB_NAME).GetCollection<BsonDocument>(CollectionNames.RawSensorMessage.ToString());


if (!RawSensorMessageDictionary.Any(p => p.Key == "_id")) //if rawSensorMessageID is empty, mongodb will set it
RawSensorMessageDictionary.Add("_id", ObjectId.GenerateNewId().ToString());
var bsonObj = new BsonDocument(RawSensorMessageDictionary);
policyColl.Save(bsonObj);

}
catch (Exception ex)
{
//log exception
}
}


And here is the code from my UnitTest:



            DataAccess.MongoDAL dal = new DataAccess.MongoDAL();
Dictionary<string, object> dic = new Dictionary<string, object>();
dic.Add("1", true);
dic.Add(Message.RESOURCE_TYPE, "aaa");
dic.Add(Message.RESOURCE_NAME, "bbb");
dic.Add(Message.SENSOR_DATA, new SensorData { Desc = "aaa", Event = true, Status = SensorStatus.Active, TTL = 4, Type = "sss", Value = "222" });
dal.SaveRawSensorData(dic );


I want my app to Serialize automatically SensorData object to BsonDocument. If I don't do it manually I'm getting the following exception: .NET type 'SensorData' cannot be mapped to a BsonValue



How should I do it?





Update 2:
OK found the issue, In my "save to db" method I used the next code in order to convert my dictionary BsonDocument:



        var bsonObj = new BsonDocument(RawSensorMessageDictionary);


I would expect that creating a new instance of 'BsonDocument' from other object will handle the conversion exactly like object.ToBsonDocument() does but apparently it's not.



Finally I replaced the code above to the following one:



    var bsonObj = RawSensorMessageDictionary.ToBsonDocument();
dal.SaveRawSensorData(dic );


now it works.










share|improve this question





























    0















    I have a Dictionary<string, object> as an insertion input for MongoDB.Save().



    When I fill this dictionary with primitive types - the serialization process works fine but when I'm trying to insert my dictionary filled with some custom class (for example - Person class) I'm getting the next error:
    .NET type 'Person' cannot be mapped to a BsonValue



    I noticed that if I insert my custom type converted to BsonDocument the serialization process work great.



    How can I define MongoDB to serialize a particular class as BsonDocument?





    Update: real code provided



        here is my SensorData class: 

    [DataContract]
    public class SensorData
    {

    [DataMember]
    [BsonElement]
    [BsonRepresentation(BsonType.String)]
    public string Type { get; set; }

    [DataMember]
    [BsonElement]
    [BsonRepresentation(BsonType.String)]
    public string Desc { get; set; }

    [DataMember]
    [BsonElement]
    [BsonRepresentation(BsonType.String)]
    public SensorStatus Status { get; set; }

    [DataMember]
    [BsonElement]
    [BsonRepresentation(BsonType.String)]
    public string Value { get; set; }

    [DataMember]
    [BsonElement]
    [BsonRepresentation(BsonType.String)]
    public string ValueUnits { get; set; }

    [DataMember]
    [BsonElement]
    [BsonRepresentation(BsonType.Boolean)]
    public bool Event { get; set; }

    [DataMember]
    [BsonElement]
    [BsonRepresentation(BsonType.Int32)]
    public int TTL { get; set; }
    }


    Here is the methods which saves the data to MongoDB:



    public void Save(Dictionary<string, object> RawSensorMessageDictionary)
    {
    try
    {
    var policyColl = new MongoClient(ConnString).GetServer().GetDatabase(DB_NAME).GetCollection<BsonDocument>(CollectionNames.RawSensorMessage.ToString());


    if (!RawSensorMessageDictionary.Any(p => p.Key == "_id")) //if rawSensorMessageID is empty, mongodb will set it
    RawSensorMessageDictionary.Add("_id", ObjectId.GenerateNewId().ToString());
    var bsonObj = new BsonDocument(RawSensorMessageDictionary);
    policyColl.Save(bsonObj);

    }
    catch (Exception ex)
    {
    //log exception
    }
    }


    And here is the code from my UnitTest:



                DataAccess.MongoDAL dal = new DataAccess.MongoDAL();
    Dictionary<string, object> dic = new Dictionary<string, object>();
    dic.Add("1", true);
    dic.Add(Message.RESOURCE_TYPE, "aaa");
    dic.Add(Message.RESOURCE_NAME, "bbb");
    dic.Add(Message.SENSOR_DATA, new SensorData { Desc = "aaa", Event = true, Status = SensorStatus.Active, TTL = 4, Type = "sss", Value = "222" });
    dal.SaveRawSensorData(dic );


    I want my app to Serialize automatically SensorData object to BsonDocument. If I don't do it manually I'm getting the following exception: .NET type 'SensorData' cannot be mapped to a BsonValue



    How should I do it?





    Update 2:
    OK found the issue, In my "save to db" method I used the next code in order to convert my dictionary BsonDocument:



            var bsonObj = new BsonDocument(RawSensorMessageDictionary);


    I would expect that creating a new instance of 'BsonDocument' from other object will handle the conversion exactly like object.ToBsonDocument() does but apparently it's not.



    Finally I replaced the code above to the following one:



        var bsonObj = RawSensorMessageDictionary.ToBsonDocument();
    dal.SaveRawSensorData(dic );


    now it works.










    share|improve this question



























      0












      0








      0


      1






      I have a Dictionary<string, object> as an insertion input for MongoDB.Save().



      When I fill this dictionary with primitive types - the serialization process works fine but when I'm trying to insert my dictionary filled with some custom class (for example - Person class) I'm getting the next error:
      .NET type 'Person' cannot be mapped to a BsonValue



      I noticed that if I insert my custom type converted to BsonDocument the serialization process work great.



      How can I define MongoDB to serialize a particular class as BsonDocument?





      Update: real code provided



          here is my SensorData class: 

      [DataContract]
      public class SensorData
      {

      [DataMember]
      [BsonElement]
      [BsonRepresentation(BsonType.String)]
      public string Type { get; set; }

      [DataMember]
      [BsonElement]
      [BsonRepresentation(BsonType.String)]
      public string Desc { get; set; }

      [DataMember]
      [BsonElement]
      [BsonRepresentation(BsonType.String)]
      public SensorStatus Status { get; set; }

      [DataMember]
      [BsonElement]
      [BsonRepresentation(BsonType.String)]
      public string Value { get; set; }

      [DataMember]
      [BsonElement]
      [BsonRepresentation(BsonType.String)]
      public string ValueUnits { get; set; }

      [DataMember]
      [BsonElement]
      [BsonRepresentation(BsonType.Boolean)]
      public bool Event { get; set; }

      [DataMember]
      [BsonElement]
      [BsonRepresentation(BsonType.Int32)]
      public int TTL { get; set; }
      }


      Here is the methods which saves the data to MongoDB:



      public void Save(Dictionary<string, object> RawSensorMessageDictionary)
      {
      try
      {
      var policyColl = new MongoClient(ConnString).GetServer().GetDatabase(DB_NAME).GetCollection<BsonDocument>(CollectionNames.RawSensorMessage.ToString());


      if (!RawSensorMessageDictionary.Any(p => p.Key == "_id")) //if rawSensorMessageID is empty, mongodb will set it
      RawSensorMessageDictionary.Add("_id", ObjectId.GenerateNewId().ToString());
      var bsonObj = new BsonDocument(RawSensorMessageDictionary);
      policyColl.Save(bsonObj);

      }
      catch (Exception ex)
      {
      //log exception
      }
      }


      And here is the code from my UnitTest:



                  DataAccess.MongoDAL dal = new DataAccess.MongoDAL();
      Dictionary<string, object> dic = new Dictionary<string, object>();
      dic.Add("1", true);
      dic.Add(Message.RESOURCE_TYPE, "aaa");
      dic.Add(Message.RESOURCE_NAME, "bbb");
      dic.Add(Message.SENSOR_DATA, new SensorData { Desc = "aaa", Event = true, Status = SensorStatus.Active, TTL = 4, Type = "sss", Value = "222" });
      dal.SaveRawSensorData(dic );


      I want my app to Serialize automatically SensorData object to BsonDocument. If I don't do it manually I'm getting the following exception: .NET type 'SensorData' cannot be mapped to a BsonValue



      How should I do it?





      Update 2:
      OK found the issue, In my "save to db" method I used the next code in order to convert my dictionary BsonDocument:



              var bsonObj = new BsonDocument(RawSensorMessageDictionary);


      I would expect that creating a new instance of 'BsonDocument' from other object will handle the conversion exactly like object.ToBsonDocument() does but apparently it's not.



      Finally I replaced the code above to the following one:



          var bsonObj = RawSensorMessageDictionary.ToBsonDocument();
      dal.SaveRawSensorData(dic );


      now it works.










      share|improve this question
















      I have a Dictionary<string, object> as an insertion input for MongoDB.Save().



      When I fill this dictionary with primitive types - the serialization process works fine but when I'm trying to insert my dictionary filled with some custom class (for example - Person class) I'm getting the next error:
      .NET type 'Person' cannot be mapped to a BsonValue



      I noticed that if I insert my custom type converted to BsonDocument the serialization process work great.



      How can I define MongoDB to serialize a particular class as BsonDocument?





      Update: real code provided



          here is my SensorData class: 

      [DataContract]
      public class SensorData
      {

      [DataMember]
      [BsonElement]
      [BsonRepresentation(BsonType.String)]
      public string Type { get; set; }

      [DataMember]
      [BsonElement]
      [BsonRepresentation(BsonType.String)]
      public string Desc { get; set; }

      [DataMember]
      [BsonElement]
      [BsonRepresentation(BsonType.String)]
      public SensorStatus Status { get; set; }

      [DataMember]
      [BsonElement]
      [BsonRepresentation(BsonType.String)]
      public string Value { get; set; }

      [DataMember]
      [BsonElement]
      [BsonRepresentation(BsonType.String)]
      public string ValueUnits { get; set; }

      [DataMember]
      [BsonElement]
      [BsonRepresentation(BsonType.Boolean)]
      public bool Event { get; set; }

      [DataMember]
      [BsonElement]
      [BsonRepresentation(BsonType.Int32)]
      public int TTL { get; set; }
      }


      Here is the methods which saves the data to MongoDB:



      public void Save(Dictionary<string, object> RawSensorMessageDictionary)
      {
      try
      {
      var policyColl = new MongoClient(ConnString).GetServer().GetDatabase(DB_NAME).GetCollection<BsonDocument>(CollectionNames.RawSensorMessage.ToString());


      if (!RawSensorMessageDictionary.Any(p => p.Key == "_id")) //if rawSensorMessageID is empty, mongodb will set it
      RawSensorMessageDictionary.Add("_id", ObjectId.GenerateNewId().ToString());
      var bsonObj = new BsonDocument(RawSensorMessageDictionary);
      policyColl.Save(bsonObj);

      }
      catch (Exception ex)
      {
      //log exception
      }
      }


      And here is the code from my UnitTest:



                  DataAccess.MongoDAL dal = new DataAccess.MongoDAL();
      Dictionary<string, object> dic = new Dictionary<string, object>();
      dic.Add("1", true);
      dic.Add(Message.RESOURCE_TYPE, "aaa");
      dic.Add(Message.RESOURCE_NAME, "bbb");
      dic.Add(Message.SENSOR_DATA, new SensorData { Desc = "aaa", Event = true, Status = SensorStatus.Active, TTL = 4, Type = "sss", Value = "222" });
      dal.SaveRawSensorData(dic );


      I want my app to Serialize automatically SensorData object to BsonDocument. If I don't do it manually I'm getting the following exception: .NET type 'SensorData' cannot be mapped to a BsonValue



      How should I do it?





      Update 2:
      OK found the issue, In my "save to db" method I used the next code in order to convert my dictionary BsonDocument:



              var bsonObj = new BsonDocument(RawSensorMessageDictionary);


      I would expect that creating a new instance of 'BsonDocument' from other object will handle the conversion exactly like object.ToBsonDocument() does but apparently it's not.



      Finally I replaced the code above to the following one:



          var bsonObj = RawSensorMessageDictionary.ToBsonDocument();
      dal.SaveRawSensorData(dic );


      now it works.







      c# mongodb serialization bson






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Oct 27 '14 at 7:48







      Ofir

















      asked Oct 26 '14 at 13:48









      OfirOfir

      2,89552452




      2,89552452
























          1 Answer
          1






          active

          oldest

          votes


















          0














          If the string in the dictionary is the property in your mongodb document, than a non primitive type is a subdocument in mongodb. Please try to mark all properties in the class with [BsonElement] and the Bson Id with [BsonId]. And be sure you follow all rules from here: Serialize Documents with the C# Driver
          It would be nice, if you provide some more information



          EDIT 1
          I would try to remove all properties of SensorData besides Value. If this works, i would than add all other (one by one).






          share|improve this answer


























          • Tried - no success

            – Ofir
            Oct 27 '14 at 7:20











          • Can you provide more code?

            – BendEg
            Oct 27 '14 at 7:21











          • One more question, should one instance of the dictionary be one document, or is every entry in the dictionary one document?

            – BendEg
            Oct 27 '14 at 7:34











          • One instance of the dictionary should be represented by one document

            – Ofir
            Oct 27 '14 at 7:38











          • OK I found the solution - see update 2, thank you

            – Ofir
            Oct 27 '14 at 7:48











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f26573668%2fset-mongodb-to-serialize-a-class-as-bsondocument%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          If the string in the dictionary is the property in your mongodb document, than a non primitive type is a subdocument in mongodb. Please try to mark all properties in the class with [BsonElement] and the Bson Id with [BsonId]. And be sure you follow all rules from here: Serialize Documents with the C# Driver
          It would be nice, if you provide some more information



          EDIT 1
          I would try to remove all properties of SensorData besides Value. If this works, i would than add all other (one by one).






          share|improve this answer


























          • Tried - no success

            – Ofir
            Oct 27 '14 at 7:20











          • Can you provide more code?

            – BendEg
            Oct 27 '14 at 7:21











          • One more question, should one instance of the dictionary be one document, or is every entry in the dictionary one document?

            – BendEg
            Oct 27 '14 at 7:34











          • One instance of the dictionary should be represented by one document

            – Ofir
            Oct 27 '14 at 7:38











          • OK I found the solution - see update 2, thank you

            – Ofir
            Oct 27 '14 at 7:48
















          0














          If the string in the dictionary is the property in your mongodb document, than a non primitive type is a subdocument in mongodb. Please try to mark all properties in the class with [BsonElement] and the Bson Id with [BsonId]. And be sure you follow all rules from here: Serialize Documents with the C# Driver
          It would be nice, if you provide some more information



          EDIT 1
          I would try to remove all properties of SensorData besides Value. If this works, i would than add all other (one by one).






          share|improve this answer


























          • Tried - no success

            – Ofir
            Oct 27 '14 at 7:20











          • Can you provide more code?

            – BendEg
            Oct 27 '14 at 7:21











          • One more question, should one instance of the dictionary be one document, or is every entry in the dictionary one document?

            – BendEg
            Oct 27 '14 at 7:34











          • One instance of the dictionary should be represented by one document

            – Ofir
            Oct 27 '14 at 7:38











          • OK I found the solution - see update 2, thank you

            – Ofir
            Oct 27 '14 at 7:48














          0












          0








          0







          If the string in the dictionary is the property in your mongodb document, than a non primitive type is a subdocument in mongodb. Please try to mark all properties in the class with [BsonElement] and the Bson Id with [BsonId]. And be sure you follow all rules from here: Serialize Documents with the C# Driver
          It would be nice, if you provide some more information



          EDIT 1
          I would try to remove all properties of SensorData besides Value. If this works, i would than add all other (one by one).






          share|improve this answer















          If the string in the dictionary is the property in your mongodb document, than a non primitive type is a subdocument in mongodb. Please try to mark all properties in the class with [BsonElement] and the Bson Id with [BsonId]. And be sure you follow all rules from here: Serialize Documents with the C# Driver
          It would be nice, if you provide some more information



          EDIT 1
          I would try to remove all properties of SensorData besides Value. If this works, i would than add all other (one by one).







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Oct 27 '14 at 7:37

























          answered Oct 26 '14 at 14:41









          BendEgBendEg

          7,25373475




          7,25373475













          • Tried - no success

            – Ofir
            Oct 27 '14 at 7:20











          • Can you provide more code?

            – BendEg
            Oct 27 '14 at 7:21











          • One more question, should one instance of the dictionary be one document, or is every entry in the dictionary one document?

            – BendEg
            Oct 27 '14 at 7:34











          • One instance of the dictionary should be represented by one document

            – Ofir
            Oct 27 '14 at 7:38











          • OK I found the solution - see update 2, thank you

            – Ofir
            Oct 27 '14 at 7:48



















          • Tried - no success

            – Ofir
            Oct 27 '14 at 7:20











          • Can you provide more code?

            – BendEg
            Oct 27 '14 at 7:21











          • One more question, should one instance of the dictionary be one document, or is every entry in the dictionary one document?

            – BendEg
            Oct 27 '14 at 7:34











          • One instance of the dictionary should be represented by one document

            – Ofir
            Oct 27 '14 at 7:38











          • OK I found the solution - see update 2, thank you

            – Ofir
            Oct 27 '14 at 7:48

















          Tried - no success

          – Ofir
          Oct 27 '14 at 7:20





          Tried - no success

          – Ofir
          Oct 27 '14 at 7:20













          Can you provide more code?

          – BendEg
          Oct 27 '14 at 7:21





          Can you provide more code?

          – BendEg
          Oct 27 '14 at 7:21













          One more question, should one instance of the dictionary be one document, or is every entry in the dictionary one document?

          – BendEg
          Oct 27 '14 at 7:34





          One more question, should one instance of the dictionary be one document, or is every entry in the dictionary one document?

          – BendEg
          Oct 27 '14 at 7:34













          One instance of the dictionary should be represented by one document

          – Ofir
          Oct 27 '14 at 7:38





          One instance of the dictionary should be represented by one document

          – Ofir
          Oct 27 '14 at 7:38













          OK I found the solution - see update 2, thank you

          – Ofir
          Oct 27 '14 at 7:48





          OK I found the solution - see update 2, thank you

          – Ofir
          Oct 27 '14 at 7:48




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f26573668%2fset-mongodb-to-serialize-a-class-as-bsondocument%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Monofisismo

          Angular Downloading a file using contenturl with Basic Authentication

          Olmecas