我已经创建了一个这样的 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/