我有一个breadcrumb表,我想返回最近插入的行。在SQL中,它将是MAX()
函数,但不确定如何在LINQ中执行等效操作。基本上我想选择具有最高BreadCrumbID WHERE ProjectID = 49
的行。
这是我现在的查询,它将选择所有行WHERE ProjectID = 49
。我想选择BreadCrumbID
最高的行。
谢谢!
代码:
using (dbPSREntities5 myEntities = new dbPSREntities5())
{
var currentStatus = (from tbBreadCrumb in myEntities.tbBreadCrumbs.Where(x => x.ProjectID == 49)
select new
{
Status = tbBreadCrumb.BreadCrumbID,
});
}
答案 0 :(得分:4)
试试这个:
using (dbPSREntities5 myEntities = new dbPSREntities5())
{
var currentStatus = (from tbBreadCrumb in myEntities.tbBreadCrumbs.Where(x => x.ProjectID == myEntities.tbBreadCrumbs.Max(b=>b.ProjectId))
select new
{
Status = tbBreadCrumb.BreadCrumbID,
});
}
答案 1 :(得分:3)
尝试以下查询
var currentStatus =
from x in myEntities.tbBreadCrumbs
where x.ProjectID == 49
orderby x.BreadCrumbID desc
select x.BreadCrumbID;
该查询的第一个结果将是BreadCrumbID
值为ProjectID
的最高值{{1}}
答案 2 :(得分:2)
此查询应该为您提供最高的BreadCrumbId,其中ProjectID = 4
using (dbPSREntities5 myEntities = new dbPSREntities5())
{
var highestId = myEntities.tbBreadCrumbs.Where(x => x.ProjectID == 49)
.Max(x => x.BreadCrumbID);
}
答案 3 :(得分:1)
您可以使用Max()
linq扩展方法
var crum = myEntities.tbBreadCrumbs.Max(d=>d.breadcrumbId)
答案 4 :(得分:1)
Var highestId = myEntities.breadcrumbs.lastOrDefault(x => x.ProjectId == 49)
答案 5 :(得分:1)
试试这个,如果ProjectID = 49中没有BreadCrumb它会给0或者给出max BreadCrumbID
using (dbPSREntities5 myEntities = new dbPSREntities5())
{
var query=myEntities.tbBreadCrumbs.Where(x => x.ProjectID == 49);
var highestId = query.Any() ? query.Max(x => x.BreadCrumbID) : 0;
}