本文介绍了4.0的EntityFramework&.CreateQuery LT; T>和排序依据例外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我认为这固定在4.0。我有这样的方法
公开的IQueryable< T>所有(表达式来; Func键< T,对象>>排序)
{
返回EntityContext.CreateQuery< T>(实体名称).AsQueryable< T>()排序依据(排序)。
}
这抛出以下异常
Any idea how to fix this or if there's any workaroundThis 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);
}
解决方案
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);
?
这篇关于4.0的EntityFramework&.CreateQuery LT; T>和排序依据例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!