Reputation: 19163
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?
Upvotes: 21
Views: 33144
Reputation: 21088
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]
Upvotes: 18
Reputation: 6371
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.
Upvotes: 3