Mongodb C# Exception Cannot Deserialize String from Bsontype Int32

mongodb C# exception Cannot deserialize string from BsonType Int32

Yes, String property in C# object has Int32 value in mongo storage, so you have exception during serialization (see code for MongoDB.Bson.Serialization.Serializers.BsonStringSerializer class).

1) You can define your own serializer, which will deserialize Int32 values to string property as well as String ones. Here it is:

public sealed class StringOrInt32Serializer : BsonBaseSerializer
{
public override object Deserialize(BsonReader bsonReader, Type nominalType,
Type actualType, IBsonSerializationOptions options)
{
var bsonType = bsonReader.CurrentBsonType;
switch (bsonType)
{
case BsonType.Null:
bsonReader.ReadNull();
return null;
case BsonType.String:
return bsonReader.ReadString();
case BsonType.Int32:
return bsonReader.ReadInt32().ToString(CultureInfo.InvariantCulture);
default:
var message = string.Format("Cannot deserialize BsonString or BsonInt32 from BsonType {0}.", bsonType);
throw new BsonSerializationException(message);
}
}

public override void Serialize(BsonWriter bsonWriter, Type nominalType,
object value, IBsonSerializationOptions options)
{
if (value != null)
{
bsonWriter.WriteString(value.ToString());
}
else
{
bsonWriter.WriteNull();
}
}
}

Then mark necessary properties (which have different types in MongoDB in your opinion) with this serializer, for example:

[BsonElement("Body")]
[BsonSerializer(typeof(StringOrInt32Serializer))]
public string Body { get; set; }

Also I've found very similar question here: Deserializing field when type is changed using MongoDb csharp driver


2) The second approach - is to 'normalize' your data in storage: convert all integer field values to string. So, you should change field $type from 16 (32-bit integer) to 2 (string). See BSON types. Let's do it for body field:

db.train.find({ 'body' : { $type : 16 } }).forEach(function (element) {   
element.body = "" + element.body; // Convert field to string
db.train.save(element);
});

Cannot deserialize string from BsonType ObjectId in MongoDb C#

Instead of using

ed.Id = Guid.NewGuid().ToString();

I used

ed.Id = MongoDB.Bson.ObjectId.GenerateNewId().ToString();

For generating Id

Its working fine : )

FormatException: Cannot deserialize a 'Guid' from BsonType 'ObjectId'

Apparently, the GUIDs I was using were not valid GUIDs. I generated them using an online generator.

I generated new ones on another website, and voilá. Everyting worked.



Related Topics



Leave a reply



Submit