Search code examples
mongodbenumerationmongodb-.net-driverdbref

Can't enumerate over objects with MongoDBRef


I have a collection called Products which I am trying to enumerate using the official mongo-csharp driver. However as soon as I try to enumerate the collection (e.g. with a foreach loop) I get the following error.

"Default constructor not found for type MongoDB.Driver.MongoDBRef"

The entity class looks like this

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

The entry in the collection looks like the following

{
    "_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")
    }
}

And i'm reading it in like this.

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

I don't get the error until I do either of the following.

var l = matches.ToList();

OR

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

Solution

    1. Connect to mongo db using mongovue and check that collection and data exists.
    2. Show code of

      var db = Db.Instance.GetDatabase();

    Should be something like this:

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

    and than yous code:

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

    3.I've checked source of mongo driver for c# and i found following in MongoDBRef

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

    So i suggest that in you version of mongo driver guys from mongo c# driver team forgot about default constructor. In any way check please that constructor exist/not exist using reflector. 4. And i am 99% sure that constructor not present at yous version of mongo driver. Because when you start to enumerate some mongo collection mongo driver going to desirealize data and in case if default constructor not found throws error.