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
How to Reference Assemblies Using Visual Studio Code
How to Convert Any Date Format to Yyyy-Mm-Dd
Post Byte Array to Web API Server Using Httpclient
How to Call Another Controller Action from a Controller in MVC
How to Read Request Body in an ASP.NET Core Webapi Controller
Regex to Remove All Special Characters from String
How to Insert 10 Million Records in the Shortest Time Possible
How to Get Group of Records With Latest Date Using Linq to Entities
How to Match Hyphens With Regular Expression
Extract First Element from Json
Calling a Function from Another Class in C#/.Net MVC App
How to Check If a Datetime Value Is Empty or Not in a Put Request
Client Specific Role Based Authentication
How to Secure the Asp.Net_Sessionid Cookie
Linq: Select an Object and Change Some Properties Without Creating a New Object