title: How to create a C# Generic Linq Querier?
body: <p>Consider a database with multiple tables built using Entity Framework code first. Each table contains a different type of object, but I wish to create a single generic query builder class for extensibility's sake. So far as a framework for this class I have a generic class as so intended to act as a wrapper for Linq to SQL:</p>
  
  <pre class="lang-cs prettyprint-override"><code>public class DBQuerier&lt;T&gt;
      where T : class
  {
      DbSet&lt;T&gt; relation;
  
      public DBQuerier(DbSet&lt;T&gt; table)
      {
          relation = table;
      }
  
      public bool Exists(T toCheck);
      public void Add(T toAdd);
      public T (Get Dictionary&lt;String, Object&gt; fields);
      public bool SubmitChanges();
      public void Update(T toUpdate, Dictionary&lt;String, Object&gt; fields);
      public void Delete(T toDelete);
  }
  </code></pre>
  
  <p>My problem comes at the first hurdle when trying to check to see if a record exists as I cannot convert between generic type T and an object type that I am trying to work with. If I use base Linq:</p>
  
  <pre class="lang-cs prettyprint-override"><code>public bool Exists(T toCheck)
  {
      return (from row in relation
          where row.Equals(toCheck)
          select row).Any();
  }
  </code></pre>
  
  <p>A run-time exception occurs as SQL cannot work with anything but primitive types even if I implement <code>IComparable</code> and designate my own Equals that compares a single field. Lambda Expressions seem to come closer, but then I get problems again with SQL not being able to handle more than primitive types even though my understanding was that <code>Expression.Equal</code> forced it to use the class' comparable function:</p>
  
  <pre class="lang-cs prettyprint-override"><code>public bool Exists(T toCheck)
  {
      ParameterExpression T1 = Expression.Parameter(typeof(myType), "T1");
      ParameterExpression T2 = Expression.Parameter(typeof(myType), "T2");
      BinaryExpression compare = Expression.Equal(T1, T2);
      Func&lt;T, T, bool&gt; checker =
          Expression.Lambda&lt;Func&lt;T, T, bool&gt;&gt;
              (compare, new ParameterExpression[] { T1, T2 }).Compile();
      return relation.Where(r =&gt; checker.Invoke(r, toCheck)).Any();
  }
  </code></pre>
  
  <p>The expression tree was designed in mind so that later I could add a switch statement to build the query according to the type I was trying to look at.
  My question is: Is there a much simpler / better way to do this (or fix what I've tried so far) as the only other options I can see are to write a class for each table (not as easy to extend) or check each record application side (potentially horrendously slow if you have to transfer the whole database!)? Apologies if I've made so very basic mistakes as I haven't worked with much of this for very long at all, thanks in advance!</p>