none
Inlining IQueryable extension method RRS feed

  • Question

  • I am trying to use the Expression Visitor from LinqKit to take a call to an extension method I wrote, and replace it in the expression tree with the expression returned:

     protected override Expression VisitMethodCall (MethodCallExpression m)
     { 
       if (m.Method.Name == "AsOf")
       {
         object query = m.Method.Invoke(m.Object, m.Arguments.ToArray());
         return (query as IQueryable).Expression;
       }

    The problem is, at runtime the type of the Arguments collection is actually an expression, instead of an IQueryable, giving me an error about failure to convert the argument from an IQueryable to Expression (since it is an extension method the arugment is the "this" parameter, i.e. the previous part of the query, which during compile time is an Iqueryable, but at runtime is an Expression).  My goal was to Invoke the below extension method, thus returning the IQueryable for the query in the extension method.  Essentially replacing the AsOf call with the query it represents, so that Linq2Entities will not choke on the "asOf" method that it would not recognize.

    public static PropertyHistory AsOf(thisIQueryable<PropertyHistory> source)
    {
      return source.SingleOrDefault(p => p.StartDate == DateTime.Now());
    }  

    Usage:

    p.PropertyHistories.AsQueryable().AsOf().Name;

    Monday, June 4, 2012 7:12 PM

Answers

  • In case anyone else stumbles upon this, this was the solution to support custom extension methods:

    http://pastebin.com/4fMjaCMV

    Example extension method, note the expression is declared separately because I was getting "unbound p" errors if it was inline.

        static Expression<Func<PropertyHistorybool>> IsCurrent = (p) => p.Starts <= DateTime.Now;
     
        [ExpandableMethod]
        public static IQueryable<PropertyHistory> AsOf(this IQueryable<PropertyHistory> source)
        {
          return source.Where(IsCurrent);
        }

    Tuesday, June 5, 2012 5:13 PM

All replies

  • In case anyone else stumbles upon this, this was the solution to support custom extension methods:

    http://pastebin.com/4fMjaCMV

    Example extension method, note the expression is declared separately because I was getting "unbound p" errors if it was inline.

        static Expression<Func<PropertyHistorybool>> IsCurrent = (p) => p.Starts <= DateTime.Now;
     
        [ExpandableMethod]
        public static IQueryable<PropertyHistory> AsOf(this IQueryable<PropertyHistory> source)
        {
          return source.Where(IsCurrent);
        }

    Tuesday, June 5, 2012 5:13 PM
  • Hi AaronLST,

    Welcome to MSDN Forum.

    I'm glad to hear that you have solved the issue, and thanks for your sharing. With your support, the forum will be better and better.

    Best Regards


    Allen Li [MSFT]
    MSDN Community Support | Feedback to us

    Wednesday, June 6, 2012 3:52 AM
    Moderator