subsonic / SubSonic-3.0-Templates

T4 Template Project for the peeps
http://subsonic.github.io/
105 stars 46 forks source link

Adding FetchByParameter back into the ActiveRecord template #23

Open jamesewelch opened 15 years ago

jamesewelch commented 15 years ago

To support backwards compatibility and make it a bit easier for us using SubSonic 2.x projects to move into 3.0. Can FetchByParameter be added back to the template?

Here's some sample code that brings back some of the same functionality by generating some dynamic Linq expressions. This code should be added to ActiveRecord.tt file near the Find methods. A better implementation would create a Comparison enum (like in 2.x) and use that instead of just using "Equals".

public static IList<<#=tbl.ClassName#>> FetchByParameter(

     string columnName, object columnValue)
{
   ParameterExpression tblExpress = 

     Expression.Parameter(typeof(<#=tbl.ClassName#>), "x");
   MemberExpression leftExpress = 

     MemberExpression.PropertyOrField(tblExpress, columnName);
   Expression rightExpress = 

     Expression.Constant(columnValue, columnValue.GetType());
   BinaryExpression binaryExpress = 

     MemberExpression.Equal(leftExpress, rightExpress);
   Expression<, bool>> expression =
      Expression.Lambda<, bool>>
         (binaryExpress, new ParameterExpression[] { tblExpress });
   expression.Compile();
   var repo = GetRepo();
   return repo.Find(expression).ToList();
}