【问题标题】:How can I condense the following Linq query into one IQueryable如何将以下 Linq 查询压缩为一个 IQueryable
【发布时间】:2010-10-18 22:51:15
【问题描述】:

我有一个 EntityFramework 模型,它的用户实体具有组织的 EntityCollection。

对于一个特定的用户,我正在尝试编写一个 Linq 查询来返回该用户所属的组织的名称,该查询只会访问数据库一次。

我的问题是我看不到如何编写此查询,而不必先具体化用户然后查询用户组织集合。

我想尝试编写一个查询数据库一次的查询。

到目前为止我所拥有的:

var orgNames = context.Users
    .Where(u => u.LoweredUserName == userName.ToLower())
    //materialises user
    .FirstOrDefault()
    .Organisations
    //second hit to the db
    .Select(o => o.Name);

我的目标是什么,但只见树木不见森林:

orgNames = context.Users
    .Where(u => u.LoweredUserName == userName.ToLower())
    //don't materialise but leave as IQueryable
    .Take(1)
    //The problem: turn what the query sees as possibly multiple
    // (due to the Take method) EntityCollection<Organisation> into a List<String>
    .Select(u => u.Organisations.Select(o => o.Name));

我看过聚合,但我似乎在绕圈子:)

【问题讨论】:

    标签: c# linq entity-framework iqueryable


    【解决方案1】:

    哇!我想我可以通过使用 SelectMany 将 Collection of Collections 压缩为一个集合来回答我自己的问题,如下所示:

    orgNames = context.Users.Where(u => u.LoweredUserName == userName.ToLower())
                    .Take(1)
                    .SelectMany(u => u.Organisations)
                    .Select(o => o.Name);
    

    【讨论】:

      【解决方案2】:

      我假设 Lowered User name 是唯一的,否则查询将毫无意义,因此您可以使用。

      context.Users
             .Where(u => u.LoweredUserName == userName.ToLower())
             .Select(u => u.Organisations.Select(o => o.Name));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-27
        • 1970-01-01
        • 1970-01-01
        • 2012-01-10
        • 1970-01-01
        相关资源
        最近更新 更多