使用mongo C#驱动程序在嵌入式文档中维护ID属性名称 [英] Maintain Id property name in embedded doc with mongo C# driver
问题描述
我有一个mongo文档,其中包含一系列嵌入式文档.嵌入的文档具有名为"Id"的属性.
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"} ] }
我的C#映射对象看起来像这样(显然是一种简化)
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; }
}
当我向数据库编写外部文件时,C#驱动程序将Inner.Id属性的名称更改为_id.我如何规避此自动重命名?我尝试在Id属性上使用[BsonElement("Id")]属性,但没有帮助.
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.
推荐答案
MongoDB文档明确指出:
MongoDB documentation explicitly states:
要求MongoDB中的文档具有唯一标识它们的键
_id
.
Documents in MongoDB are required to have a key,
_id
, which uniquely identifies them.
另一方面,C#属性通常是帕斯卡大小写的,并且不使用前缀,因此驱动程序设计器
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.
如果您要绑定一个非_id
属性,该属性只是在MongoDB中可能被称为Id
,则可以声明另一个C#属性,其名称不是Id
,因此驱动程序不会干扰它:
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; }
}
这篇关于使用mongo C#驱动程序在嵌入式文档中维护ID属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!