I'm new to MongoDb and I'm currently using the CSharp drivers (version 1.2). My problems occur when using BsonClass map. Below is the code I'm tring to execute. I've simply defined a custom type I'd like to map to a BsonDocument.
In order to use this I'm taking advantage of BsonClassMap.RegisterClassMap(). When I hit the foreach statement (trying to access the first entry in the FinAs() results) I get the following error:
'Cannot deserialize Guid from BsonType ObjectId.'
From what I understand BsonClassMap uses GuidGenerator for objects of type Guid. Why am I getting this error?
Please note that the insertion is performed without any errors...and after performing the insert, newEmployee has an EmployeeId that's been automatically generated for it.
Here's the code I'm trying to run:
class Program{
static void Main(string[] args){
MongoServer server = MongoServer.Create();
MongoDatabase dataBase = server.GetDatabase("test");
MongoCollection<Employee>employees = dataBase.GetCollection<Employee>("employees");
BsonClassMap.RegisterClassMap<Employee>(cm =>
{
cm.MapProperty(c => c.Name);
cm.MapProperty(c => c.Email);
cm.MapIdProperty(c => c.EmployeeId);
});
var newEmployee = new Employee{ Name="Test", Email="test@test.com"};
employees.Insert(newEmployee);
foreach(Employee e in employees.FindAs<Employee>(Query.EQ("Name","Test")){
Console.Writeline(e.Name);
}
}
}
public class Employee
{
public Guid EmployeeId {get;set;}
public string Name {get;set;}
public string Email {get;set;}
}
Turns out I had some additional documents stored in my collection before I started using BsonClassMap. Their ObjectId was stored in a format native to MongoDB....unfortunately this format couldn't be parsed to a Guid. To fix the error I ended up wiping out all old entries.