如何在LINQ实体中执行额外过滤的左连接?

时间:2016-08-02 07:14:30

标签: c# entity-framework linq linq-to-entities

我有几个表,主要的一个称为DefectRecord,其他表称为DefectAreaDefectLevel ...等,另一个称为DefectAttachment。这个问题是关于将DefectRecord与其他表连接以获取ViewModel以供进一步使用。我面临的困难是关于DefectAttachment表。

DefectRecordDefectAttachment具有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对象,它获取相应表的完整列表。

1 个答案:

答案 0 :(得分:1)

CodeFilterName对结果进行分组,然后将内容视为具有最早日期的组中项目的内容

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,