Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can't group by values typed as <code>object</code> in Entity Framework, unfortunately. I think there are two alternatives: you can go with returning an <code>IQueryable</code> (non-generic) object from the method, which will work if you're doing something like databinding to the result, but isn't good for much else. This allows you to ignore the type of the property you are grouping by.</p> <pre><code>public static IQueryable GroupBy&lt;TEntity&gt;( IQueryable&lt;TEntity&gt; source, string fieldName) where TEntity : class, IDataEntity { if (string.IsNullOrEmpty(fieldName)) { return new List&lt;IGrouping&lt;object, TEntity&gt;&gt;().AsQueryable(); } var parameter = Expression.Parameter(typeof(TEntity), "x"); var propertyAccess = Expression.Property(parameter, fieldName); var lambda = Expression.Lambda(propertyAccess, parameter); var groupExpression = Expression.Call( typeof(Queryable).GetMethods() .First (x =&gt; x.Name == "GroupBy") .MakeGenericMethod(new[]{ typeof(TEntity), propertyAccess.Type }), source.Expression, lambda); var result = source.Provider.CreateQuery(groupExpression); return result; } </code></pre> <p>The <code>IQueryable</code> returned from this method will be of the right type (if <code>fieldName</code> referred to an <code>int</code> property, you could cast the result to <code>IQueryable&lt;IGrouping&lt;int,TEntity&gt;&gt;</code>), but it'll be difficult to write code which can take advantage of this fact, and you won't be able to cast it to <code>IQueryable&lt;IGrouping&lt;object,TEntity&gt;&gt;</code> if <code>fieldName</code> is an <code>int</code>, because covariance doesn't work for value types.</p> <p>The other option is only available if you know the type of the property from the calling location, so that you can provide the type of the grouping key in the method arguments (this is the only way you'll be able to get back a properly typed, generic IQueryable):</p> <pre><code>public static IQueryable&lt;IGrouping&lt;TProperty,TEntity&gt;&gt; GroupBy&lt;TEntity, TProperty&gt;( IQueryable&lt;TEntity&gt; source, string fieldName) where TEntity : class, IDataEntity { if (string.IsNullOrEmpty(fieldName)) { return new List&lt;IGrouping&lt;TProperty, TEntity&gt;&gt;().AsQueryable(); } var parameter = Expression.Parameter(typeof(TEntity), "x"); var propertyAccess = Expression.Property(parameter, fieldName); var lambda = Expression.Lambda&lt;Func&lt;TEntity, TProperty&gt;&gt;(propertyAccess, parameter); var result = source.GroupBy (lambda); return result; } </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