0

I have a generic class with a method that needs to sort a generic entity.

However, an error occurs saying that it does not recognize the Reflection GetProperty method, since lambda can not translate.

How can I do this sort ordering logic?

public IEnumerable<TEntity> GetAll()
{
    var obj = _repository.GetAll()
        .OrderByDescending(x => x.GetType().GetProperty(typeof(TEntity).Name + "Id"));

    return obj.Pagination();
}

Here is the error image:

enter image description here

LeoFelipe
  • 261
  • 5
  • 13
  • 1
    Shortly: you need a helper which does order by string variable, like in [How to use a string to create a EF order by expression?](https://stackoverflow.com/questions/39908403/how-to-use-a-string-to-create-a-ef-order-by-expression), [Dynamic LINQ OrderBy on IEnumerable](https://stackoverflow.com/questions/41244/dynamic-linq-orderby-on-ienumerablet), [DynamicLINQ](https://github.com/kahanu/System.Linq.Dynamic) package etc. – Ivan Stoev Jun 24 '17 at 08:22

3 Answers3

0

The error says it all.

Linq to Entities doesn't know how to translate x.GetType().GetProperty(typeof(TEntity).Name + "Id") into SQL.

You can materialize the results first, so it'll be linq to objects:

_repository.GetAll().ToList()
    .OrderByDescending(x => x.GetType().GetProperty(typeof(TEntity).Name + "Id"));
Ofir Winegarten
  • 8,588
  • 2
  • 17
  • 25
0

You can use _repository.GetAll().Queryable().OrderByDescending(x => x.GetType().GetProperty(typeof(TEntity).Name + "Id"));

DD84
  • 313
  • 1
  • 6
  • 15
0

To build a LINQ query dynamically, use Expression Trees. This is how your method may look like:

public IEnumerable<TEntity> GetAll()
{
    IQueryable<TEntity> obj = _repository.GetAll();
    PropertyInfo keyProperty = typeof(TEntity).GetProperty(string.Concat(typeof(TEntity).Name, "Id"));
    Expression parameter = Expression.Parameter(typeof(TEntity));
    Expression predicate = Expression.Lambda(Expression.Property(parameter, keyProperty), parameter);
    Expression queryExpression = Expression.Call(typeof(Queryable), "OrderByDescending", new Type[] { typeof(TEntity), keyProperty.PropertyType }, obj, predicate);
    obj = obj.Provider.CreateQuery<TEntity>(queryExpression);
    return obj.Pagination();
}
Uranus
  • 1,641
  • 1
  • 12
  • 20