我有下面的方法FilterQuery它根据排序数据sortPropertyName属性。反过来当试图在实体框架代码中实现排序时尝试实现InvalidCastException首先使用Linq
private IQueryable<TEntity> FilterQuery(Expression<Func<TEntity, bool>> predicate, string sortPropertyName, OrderBy orderBy = OrderBy.Ascending)
{
IQueryable<TEntity> entities = _dbEntitySet;
entities = (predicate != null) ? entities.Where(predicate) : entities;
if (string.IsNullOrEmpty(sortPropertyName))
{
sortPropertyName = "Id";
}
var keySelector = CreateSelectorExpression<TEntity>(sortPropertyName);
entities = (orderBy == OrderBy.Ascending) ? entities.OrderBy(keySelector) : entities.OrderByDescending(keySelector);
return entities;
}
上述方法调用方法CreateSelectorExpression。
private static Expression<Func<TEntity, string>> CreateSelectorExpression<TEntity>(string propertyName)
{
try
{
var paramterExpression = Expression.Parameter(typeof(TEntity));
return (Expression<Func<TEntity, string>>)Expression.Lambda(Expression.PropertyOrField(paramterExpression, propertyName),
paramterExpression);
}
catch (Exception ex)
{
string msg = ex.ToString();
return null;
}
}
上述解决方案工作正常,当属性是字符串类型但抛出异常的情况下,如果属性类型是数字或日期时间。暂时你可以看到我已经硬编码Id属性来引发异常。这里是一个CreateSelectorExpression抛出返回时表达异常:
无法转换类型的对象“System.Linq.Expressions.Expression 1[System.Func
2 [MyProject.Business.Domain.MyClass,System.Int32]]”为类型“系统.Linq.Expressions.Expression 1[System.Func
2 [MyProject.Business.Domain.MyClass,System.String]]
你能帮我解决我的代码或其他更好的解决方案中发生了什么问题吗?如果您需要我提供更多信息,请让我知道。
我总是给这个链接,当我看到有关动态排序的问题时:http://stackoverflow.com/a/233505/961526 –