I need to implement an API based on extensions methods (i.e. I have to use a static non-generic class). API should work smoothly with LINQ fluent API and mostly with IQueryable arguments. Like this:
public static class SomeExtensions
{
public static IQueryable<TEntity> SomeMethod<TEntity>(this IQueryable<TEntity> set, ... some arguments)
{
}
}
Now, suppose the method should take some arguments plus an Expression<Func<TEntity, TResult>>
one:
public static IQueryable<TEntity> SomeMethod<TEntity, TResult>(
this IQueryable<TEntity> set,
...,
Expression<Func<TEntity, TResult>> orderByExpression)
{
}
I would like to pass the orderByExpression to OrderBy method of fluent API. Or do somethong else if orderByExpression == null
.
Naturally, I'd like to have something like this:
public static IQueryable<TEntity> SomeMethod<TEntity, TResult>(
this IQueryable<TEntity> set,
...,
Expression<Func<TEntity, TResult>> orderByExpression = null)
{
}
...but when calling this method w/o optional argument I have to implicitly pass generic types, because compiler doesn't know the type of TResult.
I see some possible approaches, but I don't like them much.
Define two methods: one with this argument and one w/o, and call the first from the second. I don't like it because, actually, there are many such methods in the API, and I would have to define one additional method for every one of them.
Use
Expression<Func<TEntity, object>>
instead ofExpression<Func<TEntity, TResult>>
(it is currently so). I got rid of generic type, but there is a problem with simple (value) types like int: LINQ raises an exception when trying to cast System.Int32 to System.Object.Maybe (haven't tried yet) I could use
Expression<Func<TEntity, dynamic>>
- but I don't think this is a good approach at all.
Any other ideas, anyone?