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


Question

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?

1
75
4/10/2017 9:00:49 PM

Accepted Answer

Do that like this

db.Users.OrderByDescending(u => u.UserId).FirstOrDefault();
141
12/26/2018 1:23:10 PM

try this

int intIdt = db.Users.Max(u => u.UserId);

Update:

If no record then generate exception using above code try this

int? intIdt = db.Users.Max(u => (int?)u.UserId);

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon