【问题标题】:How to correctly select data from LINQ to Entities expression?如何从 LINQ to Entities 表达式中正确选择数据?
【发布时间】:2018-11-02 08:45:42
【问题描述】:

我有两个实体:文档和附件。一份文档可能有多个或没有附件。我需要接收一个 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 的附加条目,即使它有一些附件?

【问题讨论】:

  • 您确定您使用的是 Linq To SQL 吗?现在已经过时了很长时间。也许你在谈论 EF 的 Linq To Entity?
  • 是的,对不起,我已经更正了话题

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


【解决方案1】:
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 });
                      });

【讨论】:

    【解决方案2】:

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

    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 };
    

    【讨论】:

    • 对不起,我在这个查询中得到了相同的结果。通过使用两个查询和Concat方法解决(相当于UNION)。
    猜你喜欢
    • 2018-02-20
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多