How do I get the max ID with Linq to Entity?

Ray picture Ray · Nov 25, 2008 · Viewed 130k times · Source

I have a table User which has an identity column UserID, now what is the correct Linq to Entity line of code that would return me the max UserID?

I've tried:

using (MyDBEntities db = new MyDBEntities())
{
    var User = db.Users.Last();
    // or
    var User = db.Users.Max();

    return user.UserID;
}

but Last and Max don't seem to be supported.

Any ideas?

Answer

Jonas Kongslund picture Jonas Kongslund · Nov 25, 2008

Do that like this

db.Users.OrderByDescending(u => u.UserId).FirstOrDefault();