[英]How do I get the max ID with Linq to Entity?
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
?我有一个表 User ,它有一个标识列UserID
,现在什么是正确的 Linq to Entity 代码行,它会返回最大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.但似乎不支持Last
和Max
。
Any ideas?有任何想法吗?
这样做
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);
var max = db.Users.DefaultIfEmpty().Max(r => r == null ? 0 : r.ModelID);
当 db 中没有记录时,它将毫无例外地返回 0。
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.将不起作用,因为 MAX 返回与字段相同类型的变量,因此在这种情况下是 INT 而不是用户对象。
如果您使用async
和await
功能,则如下所示:
User currentUser = await db.Users.OrderByDescending(u => u.UserId).FirstOrDefaultAsync();
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".请注意,如果键是 varchar,则这些答案都不起作用,因为很容易在充满“ints”的 varchar 列中使用 MAX。
In a database if a column eg "Id" is in the database 1,2,3, 110, 112, 113, 4, 5, 6 Then all of the answers above will return 6.在数据库中,如果一列例如“Id”在数据库中 1,2,3, 110, 112, 113, 4, 5, 6 那么上面的所有答案都将返回 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.因此,在您的本地数据库中,一切都会正常运行,因为在开发时您永远不会获得超过 100 条测试记录,然后,在生产过程中的某个时刻,您会收到一张奇怪的支持票。 Then after an hour you discover exactly this line "max" which seems to return the wrong key for some reason....一小时后,您会发现“max”这一行似乎由于某种原因返回了错误的密钥....
(and note that it says nowhere above that the key is INT...) (and if happens to end up in a generic library...) (并注意它上面没有说关键是 INT ......)(如果碰巧最终出现在通用库中......)
So use:所以使用:
Users.OrderByDescending(x=>x.Id.Length).ThenByDescending(a => a.Id).FirstOrDefault(); Users.OrderByDescending(x=>x.Id.Length).ThenByDescending(a => a.Id).FirstOrDefault();
The best way to get the id of the entity you added is like this:获取您添加的实体的 id 的最佳方法是这样的:
public int InsertEntity(Entity factor)
{
Db.Entities.Add(factor);
Db.SaveChanges();
var id = factor.id;
return id;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.