使用 mongo C# 驱动程序维护嵌入式文档中的 Id 属性名称
我有一个 mongo 文档,其中包含一组嵌入文档。嵌入文档有一个名为“Id”的属性。
{ Name: "Outer object", Embedded: [ {Name: "Embedded A", Id: "5f1c591a71dc237199eeaeda"} ] }
我的 C# 映射对象看起来像这样(显然是一种简化)
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")] 属性,但没有帮助。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
MongoDB 文档明确指出:
另一方面,C# 属性通常采用 pascal-case,并且不使用前缀,因此驱动程序设计者显然已经决定 强制将
Id
属性映射到_id
数据库属性。如果您想绑定一个非
_id
属性,而恰好在 MongoDB 中被称为Id
,您可以声明另一个带有名称的 C# 属性除了Id
之外,因此驱动程序不会干扰它:MongoDB documentation explicitly states:
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 calledId
in MongoDB, you could declare another C# property with a name other thanId
so the driver doesn't interfere with it:我同意 Dan 的回答,但在某些情况下,如果您不允许将“Id”属性更改为其他内容,您可以显式更改类映射中的行为,如下所示。
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.
我无法发表评论,所以会写新的答案。我的笔记将为人们节省大量时间。
如果 mongodb 中的 _id 是 ObjectID 类型,那么在 C# 中,您需要添加更多属性:
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: