Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to create an expression at runtime for use in GroupBy() with Entity Framework?
    primarykey
    data
    text
    <p>I am building a new extension method which will dynamically be able to group query results from Entity Framework.</p> <p>I have been able to build dynamic "where" expressions using LinqKit, but this seems to be a different animal.</p> <p>Intended usage of new extension method:</p> <pre><code>var results = entities.GroupBy("someFieldName").ToList(); </code></pre> <p>Extension method definition:</p> <pre><code> public static IQueryable&lt;IGrouping&lt;object, TEntity&gt;&gt; GroupBy&lt;TEntity&gt;( this 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 fieldXExpression = Expression.Property(parameter, fieldName); var lambda = Expression.Lambda&lt;Func&lt;TEntity, object&gt;&gt;( Expression.Convert(fieldXExpression, typeof(object)), // throws error when using EF parameter); return source.AsExpandable().GroupBy(lambda); } </code></pre> <p>I need to use <code>Expression.Convert(...)</code> because when I was testing using linqTOobjects, the code failed when the column was a <code>int32</code>. So I needed to manually convert the column to object and it worked great.</p> <p>Now that I'm testing it with EF entities, I guess that EF is trying to translate the convert to equivalent SQL, which of course I know doesn't exist.</p> <p>The error:</p> <pre><code>System.NotSupportedException: Unable to cast the type 'System.String' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types. </code></pre> <p>Is there a way to generate an expression suitable for GroupBy at runtime that is also compatible with EF?</p> <p>Thanks for any guidance.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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