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

0 votes
asked Nov 25, 2008 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?

5 Answers

0 votes
answered Nov 25, 2008 by jonas-kongslund

Try with

db.Users.OrderByDescending(u => u.UserId).FirstOrDefault()
0 votes
answered Nov 18, 2010 by minyie-diaz


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.

0 votes
answered Nov 15, 2015 by harsha-vaswani
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.

0 votes
answered Nov 12, 2016 by syed

In case if you are using the async and await feature, it would be as follows:

User currentUser = await db.Users.OrderByDescending(u => u.UserId).FirstOrDefaultAsync();
0 votes
answered Sep 15, 2017 by michel-lozada

The best way to get the id of the entity you added is like this:

public int InsertEntity(Entity factor)
    var id =;
    return id;
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter