views:

4129

answers:

5

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?

Thank you,

Ray.

+7  A: 

Try with

db.Users.OrderByDescending(u => u.UserId).FirstOrDefault()
Jonas Kongslund
+1 Was helpful to me. Thanks :)
Rashmi Pandit
+6  A: 

try this

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

A: 

Hi,

and.. if i want to add a restriction? I mean, supose that I want the max UserID where UserAge is more than 21, how can i do this?

I've try:

Users user = bd.Users.Where(u=> u.UserAge > 21).Max(u => u.UserID);

but it doesn't work... :(

A: 

Thank you so much!!

+1  A: 

NisaPrieto

Users user = bd.Users.Where(u=> u.UserAge > 21).Max(u => u.UserID); will not work because MAX returns the same type of variable that the field is so in this case is an INT not an User object.

Minyie Diaz