C# 如何使用 Linq to Entity 获取最大 ID?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/315946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get the max ID with Linq to Entity?
提问by Ray
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?
有任何想法吗?
采纳答案by Jonas Kongslund
Do that like this
这样做
db.Users.OrderByDescending(u => u.UserId).FirstOrDefault();
回答by Jonas Kongslund
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);
回答by Minyie Diaz
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 而不是用户对象。
回答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.
当 db 中没有记录时,它将毫无例外地返回 0。
回答by Psi-Ed
In case if you are using the async
and await
feature, it would be as follows:
如果您正在使用async
andawait
功能,则如下所示:
User currentUser = await db.Users.OrderByDescending(u => u.UserId).FirstOrDefaultAsync();
回答by Michel Lozada
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;
}