System.FormatException "occurred in MongoDB.Bson.dll - XXX is not a valid 24-bit hex string

I created a C # class as follows:

public class Employee { [BsonRepresentation(BsonType.ObjectId)] public string Name { get; set; } public int Age { get; set; } public List<string> Address { get; set; } } 

When I try to save this information (using MongoDB) as follows:

  var e = new Employee(); e.Address = new List<string>(); e.Address.Add("Address 1"); e.Address.Add("Address 2"); e.Age = 333; e.Name = "Some Name"; context.Employees.Insert(e); 

I get the following error:

 An unhandled exception of type 'System.FormatException' occurred in MongoDB.Bson.dll Additional information: 'Some Name' is not a valid 24 digit hex string. 

How can I create a string field as an ObjectID in MongoDB?

+6
source share
2 answers

Reading from documents:

... In this case, the serializer converts the ObjectId to a string when reading data from the database and converting the string back to ObjectId when writing data to the database (the string value must be a valid ObjectId ) ....

Remove the white space from the row. How everything should work!

To prove that you have a valid ObjectId, read the following SO-Post: MongoDB Node check if the objectid is valid

EDIT : final answer: You have to change [BsonRepresentation(BsonType.ObjectId)] to [BsonId]

+3
source

The actual ObjectId string type has a 12-byte hexadecimal string, such as '546c776b3e23f5f2ebdd3b03' .

You put [BsonRepresentation(BsonType.ObjectId)] for your Name property. this means that the C # driver will convert the string to ObjectId and vice versa automatically before any serialization.

Remove [BsonRepresentation(BsonType.ObjectId)] and

if you register BsonSerializer.RegisterIdGenerator(typeof(string), new StringObjectIdGenerator()) when you launch your application, and if you have a property named Id for your entity, mongo puts a string instead of ObjectId fields for Id, and you can use any string as a key for Id fields.

+1
source

Source: https://habr.com/ru/post/978404/


All Articles