95

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?

7 Answers 7

174

Do that like this

db.Users.OrderByDescending(u => u.UserId).FirstOrDefault();
2
  • 5
    Does somebody know the performance of this solution compared to the Max(u => u.userId) solution?
    – Felix Keil
    Commented Nov 19, 2015 at 8:36
  • 1
    I'm not sure about it but IMHO Max is more performant than Order, since Max is O(n) and Sort implies some algorithm to sort, which is way bigger than O(n).
    – Luis
    Commented Apr 11, 2016 at 21:14
122

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);
5
  • Thanks it's helpful for me int? intIdt = db.Users.Max(u => (int?)u.UserId); Commented Aug 9, 2013 at 9:44
  • 3
    Is it just me or this style is more readable than Jonas Kongslund's answer?
    – BornToCode
    Commented Nov 26, 2014 at 20:00
  • 2
    @BornToCode It depends on what you're actually trying to do. This solution answer the question (it gets the max id), whereas Jonas Kongslund's answer returns the object with the max id.
    – actaram
    Commented Jun 1, 2016 at 16:38
  • Most eloquent answer!
    – Patricia
    Commented Dec 4, 2020 at 20:02
  • 1
    Jonas's OrderByDecending method is slightly faster than using Max - 14ms / 11ms
    – tinmac
    Commented Apr 11, 2021 at 15:33
14
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.

1
  • 3
    r => r?.ModelId ?? 0 - shortcut in new C# Commented Nov 20, 2016 at 17:49
12

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.

0
3

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

Note that none of these answers will work if the key is a varchar since it is tempting to use MAX in a varchar column that is filled with "ints".

In a database if a column e.g. "Id" is in the database 1,2,3, 110, 112, 113, 4, 5, 6 Then all of the answers above will return 6.

So in your local database everything will work fine since while developing you will never get above 100 test records, then, at some moment during production you get a weird support ticket. Then after an hour you discover exactly this line "max" which seems to return the wrong key for some reason....

(and note that it says nowhere above that the key is INT...) (and if happens to end up in a generic library...)

So use:

Users.OrderByDescending(x=>x.Id.Length).ThenByDescending(a => a.Id).FirstOrDefault();

-2

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

public int InsertEntity(Entity factor)
{
    Db.Entities.Add(factor);
    Db.SaveChanges();
    var id = factor.id;
    return id;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.