title: Using Expression vs Func
body: <p>I have several autocomplete actions, one of them is listed below. Instead of writing different predicates for each autocomplete <code>Where</code> method, I have created an <code>autoCompletePredicate</code>. Since I have multiple autocompletes I am using Reflection to get the Property which is required for that specific AutoComplete and use that Property in my <code>autoCompletePredicate</code>.</p>
  
  <p>I have following code which is working alright.</p>
  
  <pre><code>static string param1, param2;
  static PropertyInfo[] properties;
  static PropertyInfo prop1, prop2;
  
  public IHttpActionResult GetAutComplete(string term, string dependent)
  {
      int pagerSize = 10;
  
      properties = new MyObject().GetType().GetProperties();
      prop1 = properties.Where(p =&gt; p.Name.ToUpper().Equals("PROP1")).FirstOrDefault();
      prop2 = properties.Where(p =&gt; p.Name.ToUpper().Equals("PROP2")).FirstOrDefault();
      param1 = term;
      param2 = dependent;
  
      return Json(context.MyObject.Where(autoCompletePredicate).Select(r =&gt; new { label = r.PROP1 }).Distinct().OrderBy(r =&gt; r.label).Take(pagerSize).ToList());
  }
  
  Func&lt;MyObject, int, bool&gt; autoCompletePredicate = (GF, index) =&gt;
  {
      bool isFound = false;
      string term, dependent;
  
      term = prop1.GetValue(GF).ToString();
      dependent = prop2.GetValue(GF).ToString();
  
      var termFound = term.Contains(param1.ToUpper());
      var dependentFound = String.IsNullOrEmpty(param2) ? true : dependent.Contains(param2.ToUpper());
  
      isFound = termFound &amp;&amp; dependentFound;
  
      return isFound;
  };
  </code></pre>
  
  <p>How can I change this code into Expression. I tried below code which compiled fine but at runtime I got the following error</p>
  
  <pre><code>public static Expression&lt;Func&lt;MyObject, bool&gt;&gt; AutoCompleteExpression()
  {
      return r =&gt; prop1.GetValue(r).ToString().Contains(param1.ToUpper()) &amp;&amp; (String.IsNullOrEmpty(param2) ? true : prop2.GetValue(r).ToString().Contains(param2.ToUpper()));
  }
  </code></pre>
  
  <blockquote>
    <p>"LINQ to Entities does not recognize the method 'System.Object
    GetValue(System.Object)' method, and this method cannot be translated
    into a store expression."</p>
  </blockquote>
  
  <p>I looked at the following <a href="https://stackoverflow.com/a/7259649/1813357">post</a> which makes absolute sense, but I am not sure how I can use that example in my scenario (which is dynamically finding properties using <strong><code>Reflection</code></strong>).</p>
  
  <p>Also, what I would like to know what can be advantage of using Expression vs Func (specially in my case)</p>