4

I'm saving a dynamic object in my database but I would also like to retrieve it as a dynamic object. How can this be done? I tried it like so:

public dynamic GetItemById(ObjectId id)
{
    dynamic result = Db.GetCollection<dynamic>("Items").Find(x => x.Id == id).FirstOrDefaultAsync().Result;
    return result;
}

But this gives me the following error:

CS1963 An expression tree may not contain a dynamic operation

I know this can be fixed by using a typed object instead of a dynamic one. But I don't want to use any typed objects, because that kind of defeats the entire purpose of using a NoSQL database like MongoDB (or at least, imho).

How can I query my collections by Id or any other property for that matter using dynamic objects?

Vivendi
  • 20,047
  • 25
  • 121
  • 196
  • What version of C# driver do you use? AFAIK, C# driver < 2.0 does not support `dynamic`, but take a look at [this answer](http://stackoverflow.com/a/21715037/4544845), maybe it is what you're looking for - especially the last comment that mentions `ExpandoObject`. – felix-b May 24 '15 at 10:17
  • @felix-b I'm using 2.0. That's why I was also able to save a `dynamic` object in the first place :) Tried to do it with an `ExpandoObject`, but you can't seem to do a `Filter` query with that either. – Vivendi May 24 '15 at 10:41

1 Answers1

7

You can use the string-based syntax, since the expression doesn't offer any advantages with dynamic anyway:

var cursor = db.GetCollection<dynamic>("foo").
                Find(Builders<dynamic>.Filter.Eq("_id", someId));
mnemosyn
  • 45,391
  • 6
  • 76
  • 82