2

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

Community
  • 1
  • 1
VahidNaderi
  • 2,448
  • 1
  • 23
  • 35
  • Can you have composite PKs? – Mathieu Guindon Aug 16 '13 at 17:36
  • It's possible, but currently a solution which works with single PKs would suffice. – VahidNaderi Aug 16 '13 at 17:43
  • It feels like you might be trying to do something else - get the count of rows, get the last identity generated, something similar? Can you not simply use the `Max` function? – Kirk Broadhurst Aug 16 '13 at 20:23
  • I need to generate identity for several tables and I can't simply just set the identity specification for the pk column so I have to do it another way and I'm thinking to implement such a method in my base repository. – VahidNaderi Aug 16 '13 at 21:16

1 Answers1

1

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;
}
Steve Ruble
  • 3,875
  • 21
  • 27