我有这种类型的代码。在Material表中,它只有一个MaterialId。但是在Report表中,它可以是多个MaterialId行。(一个materialId可以在Report表中有多个行)。
但是在Material表中我没有任何时间戳。但是在Report中有一个列为TimeStamp,我想用它来获取最新版本。
我现在只需要使用ReportAdminModel的不同值。
但是我怎么能让它像那样工作呢? 我尝试了Distinct(),但这不起作用。
list = (from material in db.Material
join reports in db.Report on material.MaterialId equals reports.MaterialId
select new ReportAdminModel
{ MaterialId = material.MaterialId, MaterialStatus = material.ProcessApprovalStatus, FlowIndex = material.FlowIndex, ActualStartTime = reports.Timestamp })
.OrderByDescending(x => x.ActualStartTime).Take(item.NumberOfRows.Value).ToList();
答案 0 :(得分:1)
如果我理解正确,请尝试:
list = (from material in db.Material
join reports in (from rep in db.Report
group rep by rep.MaterialId into grp
let latestTimeStamp = grp.Max(o => o.Timestamp)
select new
{
MaterialId = grp.Key,
Timestamp = latestTimeStamp,
//if you need any other field, just do something like :
//SomeField = grp.Where(o => o.Timestamp == latestTimeStamp).Select(o => o.SomeField).FirstOrDefault();
})
on material.MaterialId equals reports.MaterialId
select new ReportAdminModel
{MaterialId = material.MaterialId,
MaterialStatus = material.ProcessApprovalStatus,
FlowIndex = material.FlowIndex,
ActualStartTime = reports.Timestamp,
}).OrderByDescending(x => x.ActualStartTime).ToList();
答案 1 :(得分:0)
您可以group
之前应用material.MaterialId, material.ProcessApprovalStatus, material.FlowIndex
并检索每个组项的最后Timestamp
个数据。
list = (from material in db.Material
join reports in db.Report on material.MaterialId equals reports.MaterialId
group new{material,reports} by new { material.MaterialId, material.ProcessApprovalStatus, material.FlowIndex } into materialGrouped
select new ReportAdminModel
{
MaterialId = materialGrouped.Key.MaterialId,
MaterialStatus = materialGrouped.Key.ProcessApprovalStatus,
FlowIndex = materialGrouped.Key.FlowIndex,
ActualStartTime = materialGrouped.Max(x => x.reports.TimeStamp)
})
.OrderByDescending(x => x.ActualStartTime).Take(item.NumberOfRows.Value).ToList();