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?
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]