0

Ian Mercer, this is not a duplicate as you marked...2 different animals..pretty much everything in the mongodb c# driver is generic and in my case, everything (type of doc, poco etc) is known only at runtime...

I am trying to build a generic(literally) function to fetch results from collection in MongoDB using c#/.NET driver. As we are aware pretty much everything in the driver is GENERIC. Using Reflections and MakeGenericMethod to achieve these.

So far, I have reached upto executing the the equivalent of MOngoDatabase.GetCollection' . Below is my code... I am stuck at the last n final (perhaps) collection.FindAsync method.

var method_info = typeof(IMongoDatabase).GetMethod("GetCollection" );
var method_ref = method_info.MakeGenericMethod(poco_type);

object[] method_arguments = new object[] { collectionName,null };
var  collection = method_ref.Invoke(_db,  method_arguments);

MethodInfo collection_method = collection.GetType().GetMethod("FindAsync");

var collection_method_ref = collection_method.MakeGenericMethod(poco_type);

var filter_obj = new BsonDocument(filter);

method_arguments = new object[] { filter_obj,null,null };

**var result = collection_method_ref.Invoke(collection, method_arguments);**

I get error in the above line of code... Error is

"Object of type 'MongoDB.Bson.BsonDocument' cannot be converted to type
'MongoDB.Driver.FilterDefinition`1[System.RuntimeType]'."

What am I doing wrong ? I cant seem to go further. Is this even possible ?

Help greatly appreciated..

user2533922
  • 85
  • 1
  • 14
  • Object `filter_obj` that is type of `BsonDocument` is used where object of class `FilterDefinition` is expected. I hope it will resolve your query. – seahawk Sep 20 '15 at 05:23
  • seahawk...I know ..however, if you define filter this way .. in a normal circumstance (ie, doing everything as advertised) it works... since I am finidng n executing methods thru reflection..its becoming an issue.. thats where I need a solution... – user2533922 Sep 20 '15 at 06:10
  • There's more than one method called `FindAsync`, you need the correct one which is exactly the situation in the linked question. – Ian Mercer Nov 04 '15 at 19:17

0 Answers0