代码之家  ›  专栏  ›  技术社区  ›  Kevin Pang

如何避免亚音速的n+1问题?

  •  1
  • Kevin Pang  · 技术社区  · 16 年前

    Ayende有一个 blog post

    假设有两个表,“BlogPosts”和“Comments”之间有一对多的关系(即每个BlogPost可以有多个注释)。现在,假设您要执行以下嵌套for循环:

    foreach (BlogPost post in blogposts)
    {
        foreach (Comment comment in post.Comments)
        {
            // Do something
        }
    }
    

    因此,如果你有80篇博客文章,那就是用1个查询来获取博客文章的列表,然后用80个查询来获取每个博客文章的评论。但是,如果注释是预先加载的,那么这将减少到1个查询。

    目前有没有办法在亚音速下解决这个问题?

    3 回复  |  直到 16 年前
        1
  •  2
  •   John Sheehan    16 年前

    除非您创建一个查询来根据postids从评论中选择,否则我不认为有什么方法可以与之抗衡。这会让你减到两个。一个查询选择所需的post id,然后另一个查询获取该post id列表的所有注释。

        2
  •  1
  •   Yitzchok    16 年前

        3
  •  0
  •   Rick Rat    16 年前

    我也使用分部类和与加载相关的表类,如下所示:

    Partial Public Class Book
    
        Private _Author as Database.Author 
        Property Author() as Database.Author
          Get
             If _Author is nothing then
               ' Load the author class here.
             End if
             return _Author
          End get
          Set
             '....
          End Set
        End Property
    
    End Class
    
    推荐文章