如何从LINQ to Entities表达式中正确选择数据?

时间:2018-05-23 11:18:11

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

我有两个实体:文档和附件。一个文档可能有几个或没有附件。我需要收到一个IQueryable,它允许我总是为文档及其所有附件选择条目。

这是初始查询,但它只选择附件。例如,如果我有1个带有2个附件的文档,它将选择2个条目,但在这种情况下我需要有1 + 2 = 3个条目。

from d in Documents
from at in Attachments.Where(a=>a.DocumentID == d.ID).DefaultIfEmpty(null)
where d.StatusID != -1 && d.ID == 1
select new Result { ID = d.ID, AttachID = at?.ID };

目前,只有在没有任何附件的情况下,我才会收到纯文档条目。是否有可能始终包含文档的附加条目,即使它有一些附件?

2 个答案:

答案 0 :(得分:1)

您可以(左)加入文档及其附件:

var q = from d in Documents.Where(doc => doc.StatusID != -1 && doc.ID == 1)
        join a in Attachments
        on d.ID equals a.DocumentID  into docAtt
        from att in docAtt.DefaultIfEmpty()
        select new Result { ID = d.ID, AttachID = att?.ID };

答案 1 :(得分:0)

var result = Documents.Where(d => d.ID == 1 && d.StatusID != -1)
                      .GroupJoin(Attachments, d => d.ID, a => a.DocumentID,
                      (d, matchedAttachments) =>
                      {
                          //here you can do whatever with document and list of corresponding matched attachments
                          return matchedAttachments.DefaultIfEmpty().Select(ma => new Result { ID = d.ID, AttachID = ma?.ID });
                      });