【问题标题】:Can't enumerate over objects with MongoDBRef无法使用 MongoDBRef 枚举对象
【发布时间】:2010-12-09 04:53:36
【问题描述】:

我有一个名为 Products 的集合,我正在尝试使用官方 mongo-csharp 驱动程序对其进行枚举。但是,一旦我尝试枚举集合(例如使用 foreach 循环),我就会收到以下错误。

“未找到类型 MongoDB.Driver.MongoDBRef 的默认构造函数”

实体类是这样的

public partial class Product
{
    public BsonObjectId _id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string Url { get; set; }
    public int Price { get; set; }
    public string Country { get; set; }
    public MongoDBRef Merchant { get; set; }
}

集合中的条目如下所示

{
    "_id" : ObjectId("4cff739fba63c20301ee5bc5"),
    "Name" : "Product Name",
    "Description" : "Product Description",
    "Url" : "http://mysite/products/product-name",
    "Price" : 1200,
    "Country" : "au",
    "Merchant" : {
        "$ref" : "Merchant",
        "$id" : ObjectId("533981033d565e640d000000")
    }
}

我是这样读的。

var db = Db.Instance.GetDatabase();
var matches = db.GetCollection<Product>("Product").FindAll();

在执行以下任一操作之前,我不会收到错误消息。

var l = matches.ToList();

foreach (var p in matches) {
   // Do something
}

【问题讨论】:

  • 我知道你放了实体类,但是禁止你在你的问题中提供一两个示例文档?它可能有助于重新创建它。
  • 我刚刚更新了问题,贾斯汀欢呼。

标签: mongodb enumeration mongodb-.net-driver dbref


【解决方案1】:
  1. 使用 mongovue 连接到 mongo db 并检查集合和数据是否存在。
  2. 显示代码

    var db = Db.Instance.GetDatabase();

应该是这样的:

var server = MongoServer.Create("mongodb://localhost:27019");
var db =  server.GetDatabase("database_name");

比你的代码:

var matches = db.GetCollection<Product>("Product").FindAll();

3.我已经检查了 c# 的 mongo 驱动程序的源代码,我在 MongoDBRef 中发现了以下内容

 // default constructor is private and only used for deserialization
    private MongoDBRef() {
    } 

所以我建议在你们版本的 mongo 驱动程序中,来自 mongo c# 驱动程序团队的人忘记了默认构造函数。请以任何方式使用reflector 检查构造函数是否存在。 4. 我 99% 确定构造函数不存在于您的 mongo 驱动程序版本中。因为当你开始枚举一些 mongo 集合时,mongo 驱动程序会想要化数据,以防万一没有找到默认构造函数会引发错误。

【讨论】:

  • 对不起,我应该提到 Db.Instance.GetDatabase(); call 是 Create() 和 GetDatabase() 调用的包装器。我还可以确认集合和数据存在于 mongoue
  • 我是对的,这是昨天修复的 mongodb 的错误。您可以在此处查看带有修复的提交 -> github.com/mongodb/mongo-csharp-driver/commit/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-07
  • 1970-01-01
  • 1970-01-01
  • 2012-04-15
  • 2012-05-05
  • 1970-01-01
  • 2023-03-16
相关资源
最近更新 更多