Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
Basicly i want to retrive data from following collection to my Class:
[BsonIgnoreExtraElements]
public class Topic
[BsonElement("id")]
public int Id { get; set; }
[BsonElement("title")]
public string Name { get; set; }
The problem is this code doesn't work -> executes with error message:
Cannot deserialize a 'Int32' from BsonType 'ObjectId',
but this one does:
[BsonIgnoreExtraElements]
public class Topic
[BsonIgnore]
public int Id { get; set; }
[BsonElement("title")]
public string Name { get; set; }
[BsonElement("id")]
public int IdTest { get; set; }
Seems like deserialization desperatly tries to match class property with name "Id" with the ObjectId in database which is not correct because i explicitly declare that i want to match it with BsonElement("id") and not ("_id").
I appreciate any ideas how to make it works as I need to.
Your "_id" stored in your mongo document is of type BsonType.ObjectId so when deserializing, the Serializer try to find a property with the name "Id" and with type of ObjectId. In your case it found matched name but not the right type which is int (int32 type in your class): my suggestion is to change
public int Id { get; set; }
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public ObjectId Id { get; set; }
Or to make your class inheriting from class Entity if you use MongoRepository :
[BsonIgnoreExtraElements]
public class Topic : Entity
[BsonElement("title")]
public string Name { get; set; }
and this:
var list = await col.Find(new BsonDocument()).ToListAsync().ConfigureAwait(false);
foreach(var doc in list)
if(doc.Name != null)
topics.Add(new Topic{
Id = doc.Identity,
Name = doc.Name
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.