I getting the following error when trying to execute a search query in C# MongoDB.
An exception of type 'System.FormatException' occurred in MongoDB.Bson.dll but was not handled in user code Additional information: An error occurred while deserializing the FOMessages property of class XYZ: Unable to determine actual type of object to deserialize for interface type IXYZ.
The code:
public interface IMessage
{
MChannel Channel { get; }
}
MChannel is enum type.
public abstract class XYZ : IXYZ
{
public List<IXYZ> FOMessages { get; set; }
}
Below is my search query in some method SearchXYZ
.
MongoCursor<BsonDocument> searchMessages =
context.GetDatabase()
.GetCollection<BsonDocument>(typeof(Message).Name)
.Find(Query.And(searchMongoQuery));
return searchMessages
.ToList()
.Select(message => DeserializeToTypedObject(message, (MChannel)(int)message["Channel"]))
.ToList();
The DeserializeToTypedObject
method:
private Message DeserializeToTypedObject(BsonDocument document, MChannel channel)
{
switch (channel)
{
case MChannel.EMAIL:
return BsonSerializer.Deserialize<EmailMessage>(document);
case MChannel.SMS:
return BsonSerializer.Deserialize<SMSMessage>(document);
case MChannel.VOICE:
return BsonSerializer.Deserialize<VoiceMessage>(document);
default:
return null;
}
}
The code is failing in the method DeserializeToTypedObject
.
Any clues?
Thanks in advance!!
I found the solution. We were inserting the object in string format so it was failing while retrieving from mongoDB
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.