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

别等时光非礼了梦想. 提交于 2019-12-05 03:49:56

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; }
}

I agree with Dan's answer, but in some cases if you're not allowed to change the "Id" property to something else, you may explicitly change the behavior in class maps like below.

            BsonClassMap.RegisterClassMap<Inner>(cm =>
            {
                cm.AutoMap();
                cm.UnmapProperty(c => c.Id);
                cm.MapMember(c => c.Id)
                    .SetElementName()
                    .SetOrder(0) //specific to your needs
                    .SetIsRequired(true); // again specific to your needs
            });

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; }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!