我正在尝试创建一个LINQ语句,该语句返回一个记录(任务)列表及其最近分配的任务历史记录日期。因此,有两个表,第一个是任务表,其中包含有关单个任务的所有信息,然后是任务历史记录表,用于跟踪任务分配的方式和方式。这两个表都有TaskID,它们可以在连接上链接。问题是在任务历史记录中可能有许多具有相同TaskID的记录,但我只想返回具有最近分配日期的记录,该日期是任务历史记录表中的一列。我怎么能这样做?
这是我到目前为止所做的:
var query = from task in db.AP_Tasks
join taskH in db.AP_TaskHistory on task.TaskID equals taskH.TaskID
orderby new {taskH.AssignDate}
select new {task = task, assignedDate = taskH.AssignDate};
更新
最新代码:
var query = from task in db.AP_Tasks
from th in db.AP_TaskHistory
where th.TaskID == task.TaskID
orderby th.AssignDate
select new {task = task, assignDate = th.AssignDate};
答案 0 :(得分:1)
这里你需要的是一个CROSS APPLY样式查询。
select AP_Tasks.*, history.AssignDate
from AP_Tasks
cross apply (
select top 1 AP_TaskHistory.AssignDate
from AP_TaskHistory
where AP_Tasks.TaskID = AP_TaskHistory.TaskID
order by AP_TaskHistory.AssignDate DESC
) history
答案 1 :(得分:0)
我认为这样的事情对你有用。
var query = (from task in db.AP_Tasks
join taskH in db.AP_TaskHistory on task.TaskID equals taskH.TaskID
orderby new {taskH.AssignDate} descending
select new {task = task, assignedDate = taskH.AssignDate}).First();
警告,我还没有测试过这个。
您可以尝试使用.First()
代替.FirstOrDefault()
,以便更轻松地处理异常。
答案 2 :(得分:0)
这是一个让你前进的例子:
List<Task> tasks = new List<Task>();
tasks.Add(new Task {TaskID = 1});
tasks.Add(new Task {TaskID = 3});
tasks.Add(new Task {TaskID = 5});
List<TaskHistory> taskHistories = new List<TaskHistory>();
taskHistories.Add(new TaskHistory { TaskID = 3, AssignDate = DateTime.Now });
taskHistories.Add(new TaskHistory { TaskID = 3, AssignDate = DateTime.Now.AddDays(3) });
taskHistories.Add(new TaskHistory { TaskID = 1, AssignDate = DateTime.Now });
taskHistories.Add(new TaskHistory { TaskID = 1, AssignDate = DateTime.Now.AddDays(1) });
taskHistories.Add(new TaskHistory { TaskID = 1, AssignDate = DateTime.Now.AddDays(4) });
var query = from task in tasks
join thist in taskHistories on task.TaskID equals thist.TaskID
group new { t = task, date = thist.AssignDate } by task.TaskID into grouped
from g in grouped
where g.date == grouped.Max(taskInGroup => taskInGroup.date)
select g;