title: Linq Select by PK?
body: <p>Is it possible to perform a LinQ select by PK dynamically ?</p>
  
  <p>Something like that :</p>
  
  <pre><code>public T FindByPK(IEnumerable&lt;T&gt; table, T itemToFind)
  {
  
  }
  </code></pre>
  
  <p>T is a mapping from table (LinQ to SQL autogenerated).</p>
  
  <p>I tryed using reflection but I don't know how to get the attribute "IsPrimaryKey" and then perform the LinQ because sometimes the PK contains more than one column.</p>
  
  <p><strong>EDIT after Answer by chridam</strong></p>
  
  <p>So, I can now do a GetByPK but it assumes that the PK is only one column...</p>
  
  <pre><code>public static class DataContextHelpers
  {
      public static T GetByPk&lt;T&gt;(this DataContext context, object pk) where T : class {
          var table = context.GetTable&lt;T&gt;();
          var mapping = context.Mapping.GetTable(typeof(T));
          var pkfield = mapping.RowType.DataMembers.SingleOrDefault(d =&gt; d.IsPrimaryKey);
          if (pkfield == null)
              throw new Exception(String.Format("Table {0} does not contain a Primary Key field", mapping.TableName));
          var param = Expression.Parameter(typeof(T), "e");
          var predicate = Expression.Lambda&lt;Func&lt;T, bool&gt;&gt;(Expression.Equal(Expression.Property(param, pkfield.Name), Expression.Constant(pk)), param);
          return table.SingleOrDefault(predicate);
      }
  }
  </code></pre>
  
  <p>I changed the code like this to be able to get all columns of the primary keys and also, the object pk has to be a row of the table (because I don't know what are the pk columns)</p>
  
  <pre><code>public static T GetByPk&lt;T&gt;(this DataContext context, T row) where T : class
          {
              var table = context.GetTable&lt;T&gt;();
              var mapping = context.Mapping.GetTable(typeof(T));
  
              var pkfield = mapping.RowType.DataMembers.Where(d =&gt; d.IsPrimaryKey);
              if (!pkfield.Any())
                  throw new Exception(String.Format("Table {0} does not contain a Primary Key field", mapping.TableName));
              var param = Expression.Parameter(typeof(T), "e");
              var predicate = Expression.Lambda&lt;Func&lt;T, bool&gt;&gt;(Expression.Equal(Expression.Property(param, pkfield??), Expression.Property(param, row??)), param);
              return table.SingleOrDefault(predicate);
          }
  </code></pre>
  
  <p>So, I am stuck at Expression.Property who need only one property and not a group of many.</p>