c# - 如何从 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 };
目前,只有在没有任何附件的情况下,我才会收到纯文档条目。即使有一些附件,是否可以始终包含 Document 的附加条目?
解决方案
您可以(左)加入文档及其附件:
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 };