Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I've extended your functions to add support for Child Properties.</p> <pre><code>private static LambdaExpression GenerateSelector&lt;TEntity&gt;(String propertyName, out Type resultType) where TEntity : class { // Create a parameter to pass into the Lambda expression (Entity =&gt; Entity.OrderByField). var parameter = Expression.Parameter(typeof(TEntity), "Entity"); // create the selector part, but support child properties PropertyInfo property; Expression propertyAccess; if (propertyName.Contains('.')) { // support to be sorted on child fields. String[] childProperties = propertyName.Split('.'); property = typeof(TEntity).GetProperty(childProperties[0]); propertyAccess = Expression.MakeMemberAccess(parameter, property); for (int i = 1; i &lt; childProperties.Length; i++) { property = property.PropertyType.GetProperty(childProperties[i]); propertyAccess = Expression.MakeMemberAccess(propertyAccess, property); } } else { property = typeof(TEntity).GetProperty(propertyName); propertyAccess = Expression.MakeMemberAccess(parameter, property); } resultType = property.PropertyType; // Create the order by expression. return Expression.Lambda(propertyAccess, parameter); } private static MethodCallExpression GenerateMethodCall&lt;TEntity&gt;(IQueryable&lt;TEntity&gt; source, string methodName, String fieldName) where TEntity : class { Type type = typeof(TEntity); Type selectorResultType; LambdaExpression selector = GenerateSelector&lt;TEntity&gt;(fieldName, out selectorResultType); MethodCallExpression resultExp = Expression.Call(typeof(Queryable), methodName, new Type[] { type, selectorResultType }, source.Expression, Expression.Quote(selector)); return resultExp; } </code></pre> <p>You can use these functions like:</p> <pre><code>GenerateMethodCall&lt;TEntity&gt;(source, "OrderByDescending", fieldName); </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