我有几个表,主要的一个称为DefectRecord
,其他表称为DefectArea
,DefectLevel
...等,另一个称为DefectAttachment
。这个问题是关于将DefectRecord
与其他表连接以获取ViewModel以供进一步使用。我面临的困难是关于DefectAttachment
表。
DefectRecord
与DefectAttachment
具有1对多的关系。虽然一个缺陷记录可能根本没有附件,但可能有多个附件。
逻辑上我尝试在DefectRecord
&之间执行左连接。 DefectAttachment
,但还有一项要求:
CreatedDate
字段值的我坚持这个要求,如何使用LINQ-to-Entities 执行此操作?以下是我现在的代码:
var ret = (from dr in defectRecordQuery
join ft in filterQuery on dr.FilterID equals ft.FilterID
join l in levelQuery on dr.LevelID equals l.LevelID
join a in attachmentQuery on dr.DefectRecordID equals a.DefectRecordID into drd
from g in drd.DefaultIfEmpty()
select new DefectRecordViewModel
{
DefectRecordCode = dr.Code,
DefectAttachmentContent = g == null ? null : g.FileContent,
LookupFilterName = ft.FilterName,
}).ToList();
* Query变量是IQueryable
对象,它获取相应表的完整列表。
答案 0 :(得分:1)
按Code
和FilterName
对结果进行分组,然后将内容视为具有最早日期的组中项目的内容
var ret = (from dr in defectRecordQuery
join ft in filterQuery on dr.FilterID equals ft.FilterID
join l in levelQuery on dr.LevelID equals l.LevelID
join d in attachmentQuery on dr.DefectRecordID equals d.DefectRecordID into drd
from g in drd.DefaultIfEmpty()
group g by new { dr.Code, ft.FilterName } into gg
select new DefectRecordViewModel
{
DefectRecordCode = gg.Key.Code,
DefectAttachmentContent = gg.OrderByDescending(x => x.CreateDateTime).FirstOrDefault() == null? null: gg.OrderByDescending(x => x.CreateDateTime).FirstOrDefault().FileContent,
LookupFilterName = gg.Key.FilterName,
}).ToList();
如果使用C#6.0或更高版本,则可以执行以下操作:
DefectAttachmentContent = gg.OrderByDescending(x => x.CreateDateTime)
.FirstOrDefault()?.FileContent,