如何获得 Linq 到 Entity 的最大 ID?

我有一个表用户,它有一个标识列 UserID,现在什么是正确的 Linq 到实体行的代码,将返回我的最大 UserID

我试过了:

using (MyDBEntities db = new MyDBEntities())
{
var User = db.Users.Last();
// or
var User = db.Users.Max();


return user.UserID;
}

但是 LastMax似乎不被支持。

有什么想法吗?

153680 次浏览

Do that like this

db.Users.OrderByDescending(u => u.UserId).FirstOrDefault();

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);

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.

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.

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();

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;
}

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();