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

 ̄綄美尐妖づ 提交于 2020-01-02 01:36:47

问题


I have created a C# class like this:

 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) like this:

   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 am getting 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 make a string field to act as ObjectID in MongoDB?


回答1:


Reading from the docs:

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

Please remove the white space from your string. Than everything should work!

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

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




回答2:


A valid ObjectId string type has a 12bytes hex string like '546c776b3e23f5f2ebdd3b03'.

You put [BsonRepresentation(BsonType.ObjectId)] for your Property Name. that means c# driver convert a string to ObjectId and vise-versa automatically before any serialization operation.

Remove [BsonRepresentation(BsonType.ObjectId)] and

if you register BsonSerializer.RegisterIdGenerator(typeof(string), new StringObjectIdGenerator()) at your app start up, and if you have a property named Id for your entity, mongo put string instead of ObjectId for Id fields, and you can use any string as key for Id fields.



来源:https://stackoverflow.com/questions/27019513/system-formatexception-occurred-in-mongodb-bson-dll-xxx-is-not-a-valid-24-dig

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!