samedi 19 septembre 2015

MongoDB, C#, Reflection, Dynamic Execution

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..





Aucun commentaire:

Enregistrer un commentaire