Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maintain Id property name in embedded doc with mongo C# driver

I have a mongo document that contains an array of embedded documents. The embedded documents have a property named "Id".

{ Name: "Outer object", Embedded: [ {Name: "Embedded A", Id: "5f1c591a71dc237199eeaeda"} ] }

My C# mapping objects look something like this (a simplification, obviously)

public class Outer
{
    public string Name { get; set; }
    public IEnumerable<Inner> Inners { get; set; }
}

public class Inner
{
    public string Name { get; set; }
    public string Id { get; set; }
}

When I write an outer to the database, the C# driver changes the name of the Inner.Id property to _id. How do I circumvent this automatic rename? I've tried using the [BsonElement("Id")] attribute on the Id property, but it didn't help.

like image 757
Joel Harris Avatar asked Jun 29 '11 16:06

Joel Harris


2 Answers

MongoDB documentation explicitly states:

Documents in MongoDB are required to have a key, _id, which uniquely identifies them.

On the other hand, C# properties are usually pascal-case and don't use prefixes so driver designers apparently decided to force mapping Id property to _id database attribute.

If you want to bind a non-_id attribute that just happens to be called Id in MongoDB, you could declare another C# property with a name other than Id so the driver doesn't interfere with it:

public class Inner
{
    public string Name { get; set; }

    [BsonElement("Id")]
    public string IdStr { get; set; }
}
like image 163
Dan Abramov Avatar answered Oct 11 '22 13:10

Dan Abramov


I can't comment so will write new answer. My notes will save a lof of time for people. If your _id in mongodb is ObjectID type then in C# you need to add some more attributes:

[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
[BsonElement("Id")]
public string Subject { get; set; }
like image 27
Astemir Almov Avatar answered Oct 11 '22 13:10

Astemir Almov