I have a method for fetching data from database, and it is generic:
public static IQueryable<T> GetData<T>(IQueryable<T> data, some more parameters)
data is unfiltered collection of db entities, and GetData does filtering, sorting, skipping, taking upon that collection...
When I provide variable of type IQueryable (T being, for example, Document) as first parameter, as I usually do, it, of course, works:
IQueryable<Document> data = ...
GetData<Document>(data, ....);
Now, I have a need to "calculate" the first parameter dynamically. For that I use LINQ Expressions which will evaluate into IQueryable, but I dont know which T at compile time. I was thinking something like this:
Expression db = Expression.Constant(new DataModelContainer());
Expression table = Expression.Property(db, tbl); /* tbl = "Documents", this is the whole point */
Type type = table.Type.GetGenericArguments()[0];
Expression call = Expression.Call(typeof(Queryable), "AsQueryable", new Type[] { type }, table);
object o = Expression.Lambda(call, null).Compile().DynamicInvoke();
At this point o INDEED IS IQueryable (IQueryable), and as such should be able to serve as an argument to GetData. But, I have only 'object' reference to it, and naturally, cannot use it like that.
So, my question is: Is there any way to dynamically cast 'o' to 'IQueryable' when o is exactly that. I know that cast is compile time thing, but I am hoping someone has a workaround of some sort. Or maybe I am trying too much.
You can make use of the dynamic
feature. Dynamic is great for situations where you already have to do reflection:
dynamic o = Expressin.Lambda(...
Get a load of this fellah:
First. We presume the class surrounding your GetData < T > method is called Foo:
public static class Foo {
public static IQueryable<T> GetData<T>(IQueryable<T> data, int bar, bool bravo) {
// ... whatever
}
Then we try to reflect upon the MethodInfo of GetData < > (and by that I mean the actual template, generic definition, not a closed particularization of it). We try to obtain that (and succeed) at the birth of the Foo class.
private static readonly MethodInfo genericDefinitionOf_getData;
static Foo() {
Type prototypeQueryable = typeof(IQueryable<int>);
// this could be any IQuerable< something >
// just had to choose one
MethodInfo getData_ForInts = typeof(Foo).GetMethod(
name: "GetData",
bindingAttr: BindingFlags.Static | BindingFlags.Public,
binder: Type.DefaultBinder,
types: new [] { prototypeQueryable, typeof(int), typeof(bool) },
modifiers: null
);
// now we have the GetData<int>(IQueryable<int> data, int bar, bool bravo)
// reffered by the reflection object getData_ForInts
MethodInfo definition = getData_ForInts.GetGenericMethodDefinition();
// now we have the generic (non-invokable) GetData<>(IQueryable<> data, int bar, bool bravo)
// reffered by the reflection object definition
Foo.genericDefinitionOf_getData = definition;
// and we store it for future use
}
Then we write a non-generic variant of the method which should call the specific generic method with regard to the actual element type being sent as a parameter:
public static IQueryable GetDataEx(IQueryable data, int bar, bool bravo) {
if (null == data)
throw new ArgumentNullException("data");
// we can't honor null data parameters
Type typeof_data = data.GetType(); // get the type (a class) of the data object
Type[] interfaces = typeof.GetInterfaces(); // list it's interfaces
var ifaceQuery = interfaces.Where(iface =>
iface.IsGenericType &&
(iface.GetGenericTypeDefinition() == typeof(IQueryable<>))
); // filter the list down to just those IQueryable<T1>, IQueryable<T2>, etc interfaces
Type foundIface = ifaceQuery.SingleOrDefault();
// hope there is at least one, and only one
if (null == foundIface) // if we find more it's obviously not the time and place to make assumptions
throw new ArgumentException("The argument is ambiguous. It either implements 0 or more (distinct) IQueryable<T> particularizations.");
Type elementType = foundIface.GetGenericArguments()[0];
// we take the typeof(T) out of the typeof(IQueryable<T>)
MethodInfo getData_particularizedFor_ElementType = Foo.genericDefinitionOf_getData.MakeGenericMethod(elementType);
// and ask the TypeSystem to make us (or find us) the specific particularization
// of the **GetData < T >** method
try {
object result = getData_particularizedFor_ElementType.Invoke(
obj: null,
parameters: new object[] { data, bar, bravo }
);
// then we invoke it (via reflection)
// and obliviously "as-cast" the result to IQueryable
// (it's surely going to be ok, even if it's null)
return result as IQueryable;
} catch (TargetInvocationException ex) {
// in case of any mis-haps we make pretend we weren't here
// doing any of this
throw ex.InnerException;
// rethink-edit: Actually by rethrowing this in this manner
// you are overwriting the ex.InnerException's original StackTrace
// so, you would have to choose what you want: in most cases it's best not to rethrow
// especially when you want to change that which is being thrown
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With