lundi 22 janvier 2018

Using Reflection to call AsQueryable() on a MongoDB Collection

I am building an OData service for MongoDB and have needed to steer away from using BsonDocuments and so I am trying to use reflection to call the AsQueryable() method on a MongoCollection. I have the below code:

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

    var collection = method_ref.Invoke(database, new object[] { "docs", null });

    var method = typeof(IMongoCollectionExtensions).GetMethod("AsQueryable");
    var col_queryable_ref = method.MakeGenericMethod(typeof(BaseDoc));

NOTE: I have used a known type here called BaseDoc but that'll later be replaced with an emitted type via reflection

The above will all run without an error - but it hits a snag when I run

    dynamic res = col_queryable_ref.Invoke(collection, new object[] { collection, null }) as IMongoQueryable;
    return Ok(res);

While 'res' looks OK on debug inspection (not that I know what I am looking for), passing it back as a result will just generate an HTTP 406 error - so I clearly am not calling a working AsQueryable() method. If anyone has a way to call this using reflection that'd be very much appreciated!





Aucun commentaire:

Enregistrer un commentaire