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

标签 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; }
    }

当我尝试像这样保存这些信息(使用 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);

我收到以下错误:

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

Additional information: 'Some Name' is not a valid 24 digit hex string.

如何使字符串字段充当 MongoDB 中的 ObjectID

最佳答案

阅读文档:

... 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) ....

请从您的字符串中删除空格。比一切都应该工作!

要证明您是否拥有有效的 ObjectId,请阅读以下 SO-Post:MongoDB Node check if objectid is valid

编辑: 最终答案是:您必须将 [BsonRepresentation(BsonType.ObjectId)] 更改为 [BsonId]

关于c# - System.FormatException'发生在 MongoDB.Bson.dll - XXX 不是有效的 24 位十六进制字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27019513/

相关文章:

c# - 执行未知类型的 DynamicExpression

MongoDB 文本索引多词搜索太慢

c# - 在 MongoDB C# 驱动程序中获取生成的脚本

c# - 如何修复 DeleteManyAsync 返回使用过滤器删除的 0 条记录?

c# - 比较从 NHibernate 加载的对象时,== 是否保证有效?

c# - 如何定义事件然后在事件发生时启动委托(delegate)

c# - 使用不兼容的 SMTP 服务器进行身份验证

node.js - 尝试从 Jest 单元测试连接到 mongo 时超时

MongoDB 修复命令失败

c# - 使用 MongoDB 和 C# 查询数组中深度嵌套的对象