Search code examples
c#linqincludepredicates

building a predicate with no value expression


I'm trying to create an Expression<Func<T, TKey>> for IQueryable<T>.OrderByDescending()

This is in my base class for FindLast and I found that LastOrDefault will not work and thus an OrderByDescending.FirstOrDefault was necessary. However as stated it is a base class and the sort by method is the primary key so it has to be tableName + "PK"

Here is the code so far:

Expression<Func<T, object>> predicate2 = null;
string propertyName = string.Empty;
propertyName = typeof(T).Name + "PK";

ParameterExpression parameter = Expression.Parameter(typeof(T), "x");
// x.PK
MemberExpression property = Expression.Property(parameter, propertyName);
ParameterExpression[] parameters = new ParameterExpression[] { parameter };
predicate2 = Expression.Lambda<Func<T, object>>(property, parameters);

result = query.Where(predicate).OrderByDescending(predicate2).FirstOrDefault(); // .LastOrDefault();

Solution

  • Never mind, I figured it out... Needed to change predicate2 to appropriate data type

    Expression <Func <T, Int32>> predicate2