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

By : fanray

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,


By : fanray



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.

var max = db.Users.DefaultIfEmpty().Max(r => r == null ? 0 : r.ModelID);

when there are no records in db it would return 0 with no exception.

This video can help you solving your question :)
By: admin