代码之家  ›  专栏  ›  技术社区  ›  Geoff Appleford

LinqToSql-限制返回的行数时防止子查询

  •  2
  • Geoff Appleford  · 技术社区  · 16 年前
    Dim query = (From p in Parent _
                select _
                    p.ID, _
                    Tags = String.Join("|", p.Child.Select(Function(c) c.Tag.TagName).ToArray)).Take(100)
    

    在上面的查询中,当使用Take限制返回的行时,将对每一行执行单独的SQL查询以返回“Tags”字段。如果我删除Take(100),则会将单个查询发送到Sql Server。

    那么,如何限制返回的行数,同时防止为每行执行新的子查询呢?

    1 回复  |  直到 16 年前
        1
  •  2
  •   Community Mohan Dere    9 年前

    编辑2 当处理嵌套类型时,比如执行new{r,r.childrenCollection},LINQ将其转换为(从r中选择前100名),删除连接信息。当你自己加入时,这种情况不会发生。比如:

            var thingyWithChilds
                = (from p in dc.RightCategories
                   join r in dc.Rights on p.Id equals r.CategoryId
                   select new { p.Id, r });
    
            var bla = thingyWithChilds.Take(100);
    

    不会引起同样的问题。

    其他可能适用的东西

    您正在执行ToArray(),这会导致查询执行,因为它不是IQueryable。在你完成Take()之后再做ToArray()。

    编辑 Is there a LINQ equivalent of string.Join(string, string[]) ,如果要在服务器上执行所有操作,则既不能使用String.Join,因为TSQL中没有可用的SQL命令。