【问题标题】:Selecting/Filtering nested collections in L2E在 L2E 中选择/过滤嵌套集合
【发布时间】:2011-09-20 09:56:52
【问题描述】:

考虑 3 个实体。 GroupBoxMessage。每个组包含框,每个框包含消息。

Linq To Entitis 中使用 lambda 表达式检索具有自定义条件的 Group 中的消息的最佳方法是什么?

例如,我想选择某个组中昨天提交的消息(因此结果应该是IEnumerable<Message>)。我怎样才能对 db 进行最少的调用并在我的 db-query 中过滤掉结果?

更新
因未显示我的代码而遭到反对。那是因为我没有。问题很简单。不是作业。没想到!

【问题讨论】:

    标签: c# linq lambda linq-to-entities


    【解决方案1】:

    因此假设您的数据库中有外键,模型中有导航属性,下面的代码应该可以解决问题:

    var messages = context.Groups
                          .SelectMany(g => g.Boxes
                                            .SelectMany(b => b.Messages
                                                              .Where(m => m.Date ==
                                                                          yourDate)
                                                       )
                                     );
    

    【讨论】:

      【解决方案2】:

      你只需要在它们之间放置连接查询

      from g in group 
      join b in boxes on g.id = b.groupid
      join m in messages on b.id = m.boxid
      where m.Date = your date
      select m
      

      【讨论】:

      • 虽然我说过我有兴趣看到它使用 lambda 表达式,但感谢您的解决方案。
      • @Kamyar - 如果你想这样做而不是尝试 Daniel 解决方案,因为 selectmany 有意义
      猜你喜欢
      • 2017-08-03
      • 1970-01-01
      • 1970-01-01
      • 2018-06-23
      • 2021-03-02
      • 2023-01-16
      • 1970-01-01
      • 1970-01-01
      • 2020-09-06
      相关资源
      最近更新 更多