سؤال

I am trying to implement the Queryable interface and I would like to extract the type from the expression.

I have implemented the Queryable using the sample in http://blogs.msdn.com/b/mattwar/archive/2007/07/30/linq-building-an-iqueryable-provider-part-i.aspx.

When I reach the Execute method in my Provider, the expression is :

expression = {value(TestApp.HouseQueryable`1[TestApp.House]).OfType().Where(i => (i.Address == "N.125 Oxford St."))}

The first argument seem to be the type but from there on I am not sure how to extract it from the OfType() method. Can someone help me on this ?

The code to build the queryable and the query provider are the one from the tutorial.

Thanks

Edit: To expand more on my goal, I would like to query from different services depending on the type given. I know that it is not the best way to do it since i will end up having a big IF ELSE in my query provider.

By following the response of Ani, I inherited from ExpressionVisitor and checked for method call to extract the type. I only tested my scenario which is having only one .OfType() and it seems to work.

public class ExpressionTreeModifier : ExpressionVisitor
{
    public ExpressionTreeModifier(Expression expression)
    {
        this.Visit(expression);
    }

    protected override Expression VisitMethodCall(MethodCallExpression methodCall)
    {
        var method = methodCall.Method;
        if (method.Name == "OfType" && method.DeclaringType == typeof(Queryable))
        {
            var type = method.GetGenericArguments().Single();
            OfType = (Type)type;
        }
        return base.VisitMethodCall(methodCall);
    }

    public Type OfType { get;set; }
}
هل كانت مفيدة؟

المحلول

I'm not sure where you're going with this exactly, but to answer what you ask (and nothing more):

IQueryable queryable = ...

var methodCall = queryable.Expression as MethodCallExpression;

if(methodCall != null)
{
   var method = methodCall.Method;

   if(method.Name == "OfType" && method.DeclaringType == typeof(Queryable))
   {
      var type = method.GetGenericArguments().Single();
      Console.WriteLine("OfType<{0}>", type);
   }
}

Not sure how this highly specific bit of code is going to help you write your own query-provider, honestly. Could you expand a bit on your broader goals?

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top