Question

Is it possible to get max value of a pk column using EF? I mean something like find method which gets an entity based on pk values, we already have this:

public TEntity Find(params object[] keyValues);

I'm looking for something like :

public object PkMax<TEntity>();//which returns max of pk column

Update:

I'm looking for dynamic linq query based on the entity's pk and currently I know how to get the pk thanks to this SO answer: How to get the Primary Key(s) in Entity Framework 4.1, i.e. using DbContext

Was it helpful?

Solution

You'll need to manually build up the expression, so that LINQ-to-Entities can translate it into SQL for you. Since you say you can get the string name of the PK property, you can use an extension method like this:

public int GetMaxPK<T>(this IQueryable<T> query, string pkPropertyName)
{
    // TODO: add argument checks
    var parameter = Expression.Parameter(typeof(T));
    var body = Expression.Property(parameter, pkPropertyName);
    var lambda = Expression.Lambda<Func<T,int>>(body, parameter);
    var result = query.Max (lambda);
    return result;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top