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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 22:53:54  来源:igfitidea点击:

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

c#linqentity-frameworklinq-to-entities

提问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 Lastand Maxdon't seem to be supported.

但是LastMax似乎并没有得到支持。

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 asyncand awaitfeature, it would be as follows:

如果您正在使用asyncandawait功能,则如下所示:

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