在join linqc#中获取最新的记录
本文关键字:最新 记录 获取 join linqc# | 更新日期: 2023-09-27 18:05:25
我有这个查询
return from fitUpExaminationDetails in _ctx.FitUpExaminationDetails
where fitUpExaminationDetails.FitUpExaminationId == Id
join joint in _ctx.Joints on fitUpExaminationDetails.JointId equals joint.Id
join line in _ctx.Lines on joint.LineId equals line.Id
join fileIsoManager in _ctx.FileIsoManagers on line.Id equals fileIsoManager.LineId
select new ViewDomainClass.QualityControl.Report.ViewFitupExaminationReport
{
HeatNumber1 = fitUpExaminationDetails.HeatNumber1,
HeatNumber2 = fitUpExaminationDetails.HeatNumber2,
JointNumber = joint.JointNumber,
LineNumber = line.LineNumber,
Revision = fileIsoManager.Revision,
};
我的line
表可以有多个fileIsoManager
记录。所以在选择语句中,我的意思是在这部分Revision = fileIsoManager.Revision
中,我想显示fileIsoManager
表中的最新记录。我怎么能改变这个查询呢?
好吧,因为你没有提供太多的细节,我写了几个类来告诉你如何获得你的最新版本的每一行。注意"main"函数
// These are a representation of your classes :
public class Line
{
public int LineId { get; set; }
public string SomeValue { get; set;}
}
public class Revision
{
public int RevisionId { get; set; }
public int LineId { get; set;}
}
void Main()
{
// generating some data so we can test the query.
var lines = new List<Line>() {
new Line() { LineId = 1, SomeValue = "Allo!" }
};
var revisions = new List<Revision>() {
new Revision() { LineId = 1, RevisionId = 1 },
new Revision() { LineId = 1, RevisionId = 2 },
new Revision() { LineId = 1, RevisionId = 3 }
};
var result = (
from line in lines
join revision in revisions on line.LineId equals revision.LineId
group revision by line into grp
select new
{
Line = grp.Key,
LastRevision = grp.OrderByDescending(rev => rev.RevisionId).FirstOrDefault()
}
).ToList();
}
所以,基本上,你需要按行分组你的修订。在选择部分,您可以获得每行的最新版本。
在本例中,result
将包含一个动态对象,该对象包含行id=1和版本id= 3。
回到你的查询,它应该看起来像这样得到一个类似的结果:
return
from fitUpExaminationDetails in _ctx.FitUpExaminationDetails
where fitUpExaminationDetails.FitUpExaminationId == Id
join joint in _ctx.Joints on fitUpExaminationDetails.JointId equals joint.Id
join line in _ctx.Lines on joint.LineId equals line.Id
join fileIsoManager in _ctx.FileIsoManagers on line.Id equals fileIsoManager.LineId
group fileIsoManager by new { fitUpExaminationDetails, joint, line} into grp
select new ViewDomainClass.QualityControl.Report.ViewFitupExaminationReport
{
HeatNumber1 = grp.Key.fitUpExaminationDetails.HeatNumber1,
HeatNumber2 = grp.Key.fitUpExaminationDetails.HeatNumber2,
JointNumber = grp.Key.joint.JointNumber,
LineNumber = grp.Key.line.LineNumber,
Revision = grp.OrderByDescending(fileIsoMgr => gileIsoMgr.Id).FirstOrDefault()
};