MongoDB.Bson.dll中发生了System.FormatException - XXX不是有效的24位十六进制字符串

Sha*_*der 9 c# mongodb mongodb-.net-driver

我创建了一个这样的C#类:

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

当我尝试保存此信息(使用MongoDB)时,如下所示:

   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);
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

An unhandled exception of type 'System.FormatException' occurred in MongoDB.Bson.dll

Additional information: 'Some Name' is not a valid 24 digit hex string.
Run Code Online (Sandbox Code Playgroud)

如何使字符串字段ObjectID在MongoDB中起作用?

Ben*_*dEg 6

从文档中读取:

...在这种情况下,序列化程序将从数据库读取数据时将ObjectId转换为字符串,并在将数据写入数据库时​​将字符串转换回ObjectId(字符串值必须为有效的ObjectId)...。

请从字符串中删除空格。比一切都应该起作用!

为了证明您有一个有效的ObjectId,请阅读以下SO-Post:MongoDB节点,检查objectid是否有效

编辑:最终答案是:You have to change [BsonRepresentation(BsonType.ObjectId)] to [BsonId]