开发者

Entityframework 4.0 .CreateQuery<T> and OrderBy exception

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().Pro开发者_如何学Cvider.CreateQuery<T>(resultExp);
    }


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);

?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜