|
This actually works as designed. I'll explain why below and slightly change the example so that it works.
First, I would observe that it is bad practice to have two members that differ only in case, so having "Id" and "id" in the same class is a bad idea. However, the driver does support that, and is identifying the "Id" field as the _id field of the document and therefore mapping it to the "_id" element name. The "id" field in turn is mapped to the "id" element name.
Second, you can't really have an immutable Id unless you also have a constructor to set it (otherwise all your documents will have the same _id, which of course leads to duplicate key exceptions when you attempt to insert them to the database). So let's alter the class slightly:
public class ReadOnlyIdFieldClass
|
{
|
public readonly int Id;
|
public int id;
|
|
public ReadOnlyIdFieldClass(int value)
|
{
|
Id = value;
|
}
|
}
|
and now let's alter the code that inserts the documents slightly so that each document is given a different _id value:
var obj1 = new ReadOnlyIdFieldClass(1);
|
obj1.id = 123;
|
var obj2 = new ReadOnlyIdFieldClass(2);
|
obj2.id = 456;
|
|
collection.Insert(obj1);
|
collection.Insert(obj2);
|
Which now executes without a duplicate key exception and inserts the following into the database:
> db.test.find()
|
{ "_id" : 1, "id" : 123 }
|
{ "_id" : 2, "id" : 456 }
|
>
|
|