所以,我有db.Pipeline和db.JobStatus的聚合(PipelineJobStatus) 对于一个PipelineID,我可能有多个状态。我想找到最后一个,并在viewbag中调用它,以便在Edit.cshtml上预览 我需要linq。我这样想:
private IQueryable<StatusPipelineMerge> returnStatusOnID()
{
var test = (
from users in db.PipelineJobStatus
from pipe in db.Pipelines
.Where(pipe => pipe.PipelineID == users.PipelineID).DefaultIfEmpty()
from status in db.JobStatus
.Where(statuses => statuses.JobStatusID == users.JobStatusID).DefaultIfEmpty()
from fco in db.FCOes
.Where(fcoes => fcoes.FCOID == pipe.FCOID)
from client in db.Clients
.Where(clients => clients.ClientID == pipe.ClientID)
orderby users.CreatedTimeStamp descending
select new StatusPipelineMerge
{
JobStatusName = status.JobStatusName
}
);
return (test);
}
我之所以放下原因,只是抓住堆栈上的第一个日期(FirstOrDefault)。我能这样做吗?或者我需要MAX功能? 我正在使用EF6 谢谢!
答案 0 :(得分:2)
当您按顺序排序FirstOrDefault()
时(假设可能没有任何你想要的东西。
如果您订购升序,则会使用LastOrDefault()
。
要么是好的,那就去使你的代码最容易理解。
答案 1 :(得分:0)
简直就是这样:
private StatusPipelineMerge returnStatusOnID()
{
var test = (from users in db.PipelineJobStatus
orderby users.CreatedTimeStamp descending
select new StatusPipelineMerge
{
JobStatusName = users.JobStatus.JobStatusName
}).FirstOrDefault();
return (test);
}
我不了解这些连接的需要,也没有理解&#34; left join&#34;处理PipelineJobStatus和JobStatus之间的这种关系。
答案 2 :(得分:0)
使用着名的Northwind示例数据库和EF:
var lastPurchaseCustomer =
(from o in Orders
orderby o.OrderDate descending
select new
{
TheID = o.Customer.CustomerID
}).FirstOrDefault();
Console.WriteLine(lastPurchaseCustomer.TheID);
将此SQL发送到服务器:
SELECT TOP (1)
[Project1].[C1] AS [C1],
[Project1].[CustomerID] AS [CustomerID]
FROM ( SELECT
[Extent1].[CustomerID] AS [CustomerID],
[Extent1].[OrderDate] AS [OrderDate],
1 AS [C1]
FROM [dbo].[Orders] AS [Extent1]
) AS [Project1]
ORDER BY [Project1].[OrderDate] DESC
并打印(我也可以从Order.CustomerID获取,但这里也可以要求CompanyName,ContactName等):
RATTC