MongoDB C# BsonRepresentation of an Array of ObjectIds

本文关键字:of Array ObjectIds an MongoDB BsonRepresentation | 更新日期: 2023-09-27 18:35:27

>我有这样的文档方案:

{
  "_id" : ObjectId("4fbb728d80db260988580e05"),
  "titleFull" : "Foo, Inc",
  "titleShort" : "Foo",
  "countries" : [
     ObjectId("4fba04ef80db260988f8b607"),
     ObjectId("4fba05f880db260988cd5cfd") ],
  "type" : "company"
}

MVC 4 Web API 项目中 ASP.NET 这样的类:

public class Company
{
  [BsonRepresentation(BsonType.ObjectId)]
  public String id { get; set; }
  public String titleFull { get; set; }
  public String titleShort { get; set; }
  //[BsonRepresentation(BsonType.ObjectId)]
  //public String[] countries { get; set; } — not working
  public ObjectId[] countries { get; set; }
  public String type { get; set; }
}

当我在收到 JSON 文档/api/countries发送 GET 请求时(这是 mvc 反序列化):

{
  "id": "4fba097e80db2609886ce7f2",
  "titleFull": "Foo, LLC",
  "titleShort": "Foo",
  "countries": [
    {
      "_increment": 16299527
      "_machine": 8444710
      "_pid": 2440
      "_timestamp": 1337591023
    },
    {
      "_increment": 13458685
      "_machine": 8444710
      "_pid": 2440
      "_timestamp": 1337591288
    }
  ],
  "type": "company"
}

有没有办法像这样做 JSON 响应:

{
  "id": "4fba097e80db2609886ce7f2",
  "titleFull": "Foo, LLC",
  "titleShort": "Foo",
  "countries": ["4fba04ef80db260988f8b607","4fba05f880db260988cd5cfd"],
  "type": "company"
}

MongoDB C# BsonRepresentation of an Array of ObjectIds

给未来读者的注意

Rober Stam在谷歌群组中写道:

反序列化代码中存在错误。在数组的情况下,[BsonRepresentation] 属性实际上应用于项目而不是数组。

我为此创建了一个 JIRA 票证:

https://jira.mongodb.org/browse/CSHARP-479

因此,如果您有同样的问题,请跟踪此票证。

在响应中,不使用 ObjectId for Country,请使用字符串数组,并添加要在 json 响应中传递的 id。

公共字符串[] 国家 { get; set; }

如果你这样使用,响应在 JSON 中将是这样的

"国家": ["4FBA04ef80db260988f8b607","4fba05f880db260988cd5cfd"],

您正在使用 id 字段中已有的字符串。