Note that there are some explanatory texts on larger screens.

plurals
  1. POEntityframework 4.0 .CreateQuery<T> and OrderBy exception
    primarykey
    data
    text
    <p>I thought this was fixed in 4.0. I have this method </p> <pre><code>public IQueryable&lt;T&gt; All(Expression&lt;Func&lt;T,object&gt;&gt; sort) { return EntityContext.CreateQuery&lt;T&gt;(EntityName).AsQueryable&lt;T&gt;().OrderBy(sort); } </code></pre> <p>this throws the following exception</p> <blockquote> <p>Unable to cast the type 'System.Int32' to type 'System.Object'. LINQ to Entities only supports casting Entity Data Model primitive types. Source is System.Data.Entity</p> </blockquote> <p>Any idea how to fix this or if there's any workaround This happens with every call when the order is not a string datatype</p> <pre><code>IQueryable&lt;Blog&gt; sortedAll = _repository.All(x =&gt; x.Title); </code></pre> <p>since Title is a string the orderBy works fine. but it fails with any other datatypes</p> <p>Since I came up with this "bad" solution before I seen Marc's. I thought I post it </p> <pre><code>public IQueryable&lt;T&gt; All(Expression&lt;Func&lt;T,object&gt;&gt; sort) { var expresssionType = sort.Body.GetType(); string propertyName= expresssionType == typeof(System.Linq.Expressions.UnaryExpression) ? ((MemberExpression)((UnaryExpression)sort.Body).Operand).Member.Name : ((MemberExpression)sort.Body).Member.Name; var items= EntityContext.CreateQuery&lt;T&gt;(EntityName).AsQueryable&lt;T&gt;(); var type = typeof(T); var expressionProperty = type.GetProperty(propertyName); var exPressionparameter = Expression.Parameter(type, "p"); var propertyAccess = Expression.MakeMemberAccess(exPressionparameter, expressionProperty); var orderByExp = Expression.Lambda(propertyAccess, exPressionparameter); Expression resultExp = Expression.Call(typeof(Queryable), "OrderBy", new Type[] { type, expressionProperty.PropertyType }, items.Expression, Expression.Quote(orderByExp)); return items.AsQueryable().Provider.CreateQuery&lt;T&gt;(resultExp); } </code></pre>
    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