问题描述:

I have the following repository method that applies a filter and then orders the collection:

 public IQueryable<TE> SelectAll(Expression<Func<TE, bool>> predicate,

Expression<Func<TE, object>> sortExpression, bool orderDescending = false)

{

var list = _ctx.CreateQuery<TE>("[" + typeof(TE).Name + "]")

.AsExpandable().Where(predicate);

return orderDescending

? list.OrderByDescending(sortExpression)

: list.OrderBy(sortExpression);

}

The where predicate works fine, but when if the OrderBy is applied we get the following error:

Unable to cast the type 'System.Int32' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types.

Edit: This is the calling code:

 var documentos = SelectAll(d => serviciosId.Contains(d.ServicioId) && d.TipoSociedadId == tipoSociedadId, d => d.Grupo);

网友答案:

Try this:

public IQueryable<TE> SelectAll<TE, TKey>(Expression<Func<TE, bool>> predicate, 
            Expression<Func<TE, TKey>> sortExpression, bool orderDescending = false)
{
    var list = _ctx.CreateQuery<TE>("[" + typeof(TE).Name + "]")
                   .AsExpandable().Where(predicate);

    return orderDescending 
        ? list.OrderByDescending(sortExpression) 
        : list.OrderBy(sortExpression);
}

The problem is that the second parameter of the Func in the OrderBy clause is object in your code, and you are passing it an int, then it tries to cast that int to object. In the code I pasted above, you have an extra generic parameter that allows you to pass in any type for the ordering function, so, that should work.

相关阅读:
Top