title: How can I generate chained method expressions for LINQ and Entity Framework at runtime?
body: <p>I am working a a small library that generates 'where' expressions at runtime. I've been able to navigate object properties and query using different operators like <code>Expression.Equal</code>, <code>Expression.NotEqual</code> and even the <code>.Contains()</code> method on strings.</p>
  
  <p>I've run into a situation where I need to create an expression that represents chained methods, like this: <code>x =&gt; x.SomeColumn.Trim().EndsWith("SomeText")</code>. I'm not sure where to start with this.</p>
  
  <p>I've implemented the <code>.EndsWith()</code> method already like this:</p>
  
  <pre><code>static Expression&lt;Func&lt;TEntity, bool&gt;&gt; GetEndsWithExpression(
      ParameterExpression parameterExpression,
      Expression propertyExpression,
      Expression valueToFind)
  {
      var propertyExp = propertyExpression;
      var method = typeof(string).GetMethod("EndsWith", new[] { typeof(string) });
      var someValue = valueToFind;
      var containsMethodExp = Expression.Call(propertyExp, method, someValue);
  
      return Expression.Lambda&lt;Func&lt;TEntity, bool&gt;&gt;(containsMethodExp, parameterExpression);
  }
  </code></pre>
  
  <p>I'm wondering if you can help me figure out how to add the <code>.Trim()</code> method and chain it with the <code>.EndsWith()</code> method. </p>
  
  <p>Some other info, I'm already using LINQKit in my project, so things like <code>.AsExpandable()</code> are somewhat familiar to me.</p>
  
  <h2>My initial (wrong) approach (Updated)</h2>
  
  <p>I think that a solution would look something like this: </p>
  
  <pre><code>static Expression&lt;Func&lt;TEntity, bool&gt;&gt; GetTrimEndsWithExpression(
      ParameterExpression parameterExpression,
      Expression propertyExpression,
      Expression valueToFind)
  {
      var propertyExp = propertyExpression;
  
      var trimMethod = typeof(string).GetMethod("Trim");
      var endsWithMethod = typeof(string).GetMethod("EndsWith", new[] { typeof(string) });
  
      var trimMethodExpression = Expression.Call(propertyExp, trimMethod).Expand();
      var containsMethodExp = Expression.Call(trimMethodExpression, endsWithMethod, valueToFind);
  
      return Expression.Lambda&lt;Func&lt;TEntity, bool&gt;&gt;(containsMethodExp, parameterExpression);
  }
  </code></pre>
  
  <p>However, this fails to compile. It throws an error: </p>
  
  <pre><code>System.Reflection.AmbiguousMatchException: Ambiguous match found.
  </code></pre>
  
  <p>How do I go about chaining these two methods in an expression generated at runtime?</p>