Query mongodb collection as dynamic

送分小仙女□ 提交于 2019-12-12 16:19:15

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/30421818/query-mongodb-collection-as-dynamic

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!