[英]How do I traverse three tables and get the maximum of a value
In my EntityFramework I have three associated tables like so: 在我的EntityFramework中,我有三个相关的表,如下所示:
I'm trying to get the last time a file was used on a job. 我试图让最后一次在工作中使用文件。 I have a value for File.Name and I need to get the maximum value for Job.ExecutedOn. 我有一个File.Name的值,我需要获得Job.ExecutedOn的最大值。 I can obtain the File.FileId with a where clause, then in a separate expression get a list of FileHistory.JobId, then finally in a third expression get the maximum of Job.ExecutedOn. 我可以使用where子句获取File.FileId,然后在单独的表达式中获取FileHistory.JobId列表,最后在第三个表达式中获取Job.ExecutedOn的最大值。 It feels very clumsy. 感觉非常笨拙。
I was hoping for a single expression that accepts a value for File.Name and traverses across the tables to return the maximum value for Job.ExecutedOn. 我希望有一个表达式接受File.Name的值,并遍历表以返回Job.ExecutedOn的最大值。 Is this possible? 这可能吗? How? 怎么样?
This should do the trick 这应该可以解决问题
DateTime GetLastExecutionTime(ObjectContext context, string fileName)
{
var query = from file in context.Files
join history in context.FileHistories
on file.FileID equals history.FileID
join job in context.Jobs
on history.JobID equals job.JobID
where file.FileName == fileName
select job.ExecutedOn;
var result = query.Max();
}
I believe this will work for you: 我相信这对你有用:
var query =
from file in dc.Files
where file.Name == fileName
from history in file.FileHistories
orderby history.Job.ExecutedOn descending
select history.Job.ExecutedOn;
var lastExecutedDate = query.First();
I wrote it in a way so you could easily return the associated job instead. 我以某种方式编写它,以便您可以轻松返回相关的作业。 To do that just change the final projection to select history.Job
. 要做到这一点,只需更改最终投影以select history.Job
。
Otherwise you could just remove the sort and take the Max()
of the query (instead of First()
). 否则你可以删除排序并获取查询的Max()
(而不是First()
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.