title: Can I dynamically build a where clause in LINQ to Entities?
body: <p>I'm trying to dynamically build a LINQ query for LINQ to Entities so that I can avoid repeating the same function twice.</p>
  
  <p>Here is what I'm trying to do:</p>
  
  <pre><code>private IUser GetOrUpdateUser(Predicate&lt;IUser&gt; filter, Func&lt;IIdentityProvider, UserRecord&gt; fetch)
  {
      var user = (from u in this.adapter.Users
                  where filter(u)
                  select u).SingleOrDefault();
  
      if (user == null)
      {
          // User not found.  Add him.
          user = this.adapter.AddUser(fetch(this.idenityProvider));
      }
      else if (user.IsExpired)
      {
          // User found, but expired.  Update him.
          this.adapter.UpdateUser(user, fetch(this.idenityProvider));
      }
  
      return user;
  }
  
  protected IUser GetUserByNetworkId(string username)
  {
      return GetOrUpdateUser(
          u =&gt; u.NetworkId == username,
          i =&gt; i.GetUserByNetworkId(username));
  }
  
  protected IUser GetUserByEmail(string email)
  {
      return GetOrUpdateUser(
          u =&gt; u.Email == email,
          i =&gt; i.GetUserByEmail(email));
  }
  </code></pre>
  
  <p>The <code>filter</code> parameter is throwing this exception:</p>
  
  <blockquote>
    <p>The LINQ expression node type 'Invoke' is not supported in LINQ to Entities</p>
  </blockquote>
  
  <p>I could potentially do this:</p>
  
  <pre><code>protected IUser GetUserByNetworkId(string username)
  {
      return GetOrUpdateUser(
          from u in this.adapter.Users
          where u.NetworkId == username
          select u,
          i =&gt; i.GetUserByNetworkId(username));
  }
  
  protected IUser GetUserByEmail(string email)
  {
      return GetOrUpdateUser(
          from u in this.adapter.Users
          where u.Email == email
          select u,
          i =&gt; i.GetUserByEmail(email));
  }
  </code></pre>
  
  <p>But, that is not as clean.</p>
  
  <p>Any suggestion?</p>