An unhandled exception of type 'System.ArgumentException' occurred in System.Core.dll Additional information: Expression of type 'System.Linq.IQueryable`1[T]' cannot be used for parameter of type 'MongoDB.Driver.Linq.IMongoQueryable`1[T]' of method 'MongoDB.Driver.Linq.IMongoQueryable`1[T] Sample[SubAgg] (MongoDB.Driver.Linq.IMongoQueryable`1[T], Int64)'
This is coming from a relatively simple query: collection.AsQueryable().Where().OrderBy().Sample();
The reason for the exception is that
1. tho the operations in MongoQueryable are defined as IMongoQueryable<T> Operation(this IMongoQueryable<T>,...)
2. They call into the original LINQ implementation (IMongoQueryable<TResult>)Queryable.Operation(source, ...)
3. Thus they return an Expression with the Type IQueryable<T> (source.Expression.Type)
Sample() creates the expression using Expression.Call, but its method signature does not "accept" the expression (as per the validations inside Expression.Call).
The solution is to change the method signature to
public static IMongoQueryable<TSource> Sample<TSource>(this IQueryable<TSource> source, long count)
Not sure if this solution is acceptable, but haven't found any better way (without reimplementing all LINQ operations so they have IMongoQueryable as their Expression.Type)
I have a pull request & a simple unit test which I can submit if you want it
https://github.com/enyim/mongo-csharp-driver/commit/0910aa62b26a7c4460fa83ed03cb87e52a89c971