Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>What you need is to build an expression tree that <a href="http://en.wikipedia.org/wiki/Language_Integrated_Query#LINQ_to_SQL" rel="noreferrer">LINQ&nbsp;to&nbsp;SQL</a> can understand. Assuming your "id" property is always named "id":</p> <pre><code>public virtual T GetById&lt;T&gt;(short id) { var itemParameter = Expression.Parameter(typeof(T), "item"); var whereExpression = Expression.Lambda&lt;Func&lt;T, bool&gt;&gt; ( Expression.Equal( Expression.Property( itemParameter, "id" ), Expression.Constant(id) ), new[] { itemParameter } ); var table = DB.GetTable&lt;T&gt;(); return table.Where(whereExpression).Single(); } </code></pre> <p>This should do the trick. It was shamelessly borrowed from <a href="http://mikehadlow.blogspot.com/2008/03/using-irepository-pattern-with-linq-to.html" rel="noreferrer">this blog</a>. This is basically what LINQ&nbsp;to&nbsp;SQL does when you write a query like</p> <pre><code>var Q = from t in Context.GetTable&lt;T)() where t.id == id select t; </code></pre> <p>You just do the work for LTS because the compiler cannot create that for you, since nothing can enforce that T has an "id" property, and you cannot map an arbitrary "id" property from an interface to the database.</p> <p>==== UPDATE ====</p> <p>OK, here's a simple implementation for finding the primary key name, assuming there is only one (not a composite primary key), and assuming all is well type-wise (that is, your primary key is compatible with the "short" type you use in the GetById function):</p> <pre><code>public virtual T GetById&lt;T&gt;(short id) { var itemParameter = Expression.Parameter(typeof(T), "item"); var whereExpression = Expression.Lambda&lt;Func&lt;T, bool&gt;&gt; ( Expression.Equal( Expression.Property( itemParameter, GetPrimaryKeyName&lt;T&gt;() ), Expression.Constant(id) ), new[] { itemParameter } ); var table = DB.GetTable&lt;T&gt;(); return table.Where(whereExpression).Single(); } public string GetPrimaryKeyName&lt;T&gt;() { var type = Mapping.GetMetaType(typeof(T)); var PK = (from m in type.DataMembers where m.IsPrimaryKey select m).Single(); return PK.Name; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload