views:

101

answers:

1

Hi Guys, I thought this was fixed in 4.0. I have this method

public IQueryable<T> All(Expression<Func<T,object>> sort)
    {
       return EntityContext.CreateQuery<T>(EntityName).AsQueryable<T>().OrderBy(sort);
    }

this throws the following exception

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

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

IQueryable<Blog> sortedAll = _repository.All(x => x.Title);

since Title is a string the orderBy works fine. but it fails with any other datatypes

Since I came up with this "bad" solution before I seen Marc's. I thought I post it

public IQueryable<T> All(Expression<Func<T,object>> 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<T>(EntityName).AsQueryable<T>();
        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<T>(resultExp);
    }
+2  A: 

I can't change the runtime, but can't you just work around it? i.e.

public IQueryable<T> All<TValue>(Expression<Func<T,TValue>> sort)
{
    return EntityContext.CreateQuery<T>(EntityName)
           .AsQueryable<T>().OrderBy<T,TValue>(sort);
}

and

IQueryable<Blog> sortedAll = _repository.All(x => x.SomeProp);

?

Marc Gravell
Thanks Marc,Your solution is much better what I came up with.
Sammy