title: Iterate through dbset to get next n rows
body: <p>I'm trying to find out what's a good way to continually iterate through a dbset over various function calls, looping once at the end. </p>
  
  <p>Essentially I've got a bunch of Ads in the database, and I want to getNext(count) on the dbset.Ads</p>
  
  <p>Here's an example</p>
  
  <pre><code>ID   Text   Other Columns...
  1    Ad1    ...
  2    Ad2    ...
  3    Ad3    ...
  4    Ad4    ...
  5    Ad5    ...
  6    Ad6    ...
  </code></pre>
  
  <p>Let's say that in my View, I determine I need 2 ads to display for User 1. I want to return Ads 1-2. User 2 then requests 3 ads. I want it to return 3-5. User 3 needs 2 ads, and the function should return ads 6 and 1, looping back to the beginning.</p>
  
  <p>Here's my code that I've been working with (it's in <code>class AdsManager</code>):</p>
  
  <pre><code>Ad NextAd = db.Ads.First();
  public IEnumerable&lt;Ad&gt; getAds(count)
  {
      var output = new List&lt;Ad&gt;();
      IEnumerable&lt;Ad&gt; Ads = db.Ads.OrderBy(x=&gt;x.Id).SkipWhile(x=&gt;x.Id != NextAd.Id);
      output.AddRange(Ads);
  
      //If we're at the end, handle that case
      if(output.Count != count)
      {
          NextAd = db.Ads.First();
          output.AddRange(getAds(count - output.Count));
      }
      NextAd = output[count-1];
  
      return output;
  }
  </code></pre>
  
  <p>The problem is that the function call <code>IEnumerable&lt;Ad&gt; Ads = db.Ads.OrderBy(x=&gt;x.Id).SkipWhile(x=&gt;x.Id != NextAd.Id);</code> throws an error on <code>AddRange(Ads)</code>:</p>
  
  <p>LINQ to Entities does not recognize the method 'System.Linq.IQueryable'1[Domain.Entities.Ad] SkipWhile[Ad](System.Linq.IQueryable'1[Domain.Entities.Ad], System.Linq.Expressions.Expression'1[System.Func`2[Domain.Entities.Ad,System.Boolean]])' method, and this method cannot be translated into a store expression. </p>
  
  <p>I originally had loaded the entire dbset into a Queue, and did enqueue/dequeue, but that would not updat when a change was made to the database. I got the idea for this algorithm based on <a href="https://stackoverflow.com/questions/12664638/get-the-next-and-previous-sql-row-by-id-and-name-ef">Get the next and previous sql row by Id and Name, EF?</a></p>
  
  <p>What call should I be making to the database to get what I want?</p>
  
  <p>UPDATE: Here's the working Code:</p>
  
  <pre><code>public IEnumerable&lt;Ad&gt; getAds(int count)
      {
          List&lt;Ad&gt; output = new List&lt;Ad&gt;();
  
          output.AddRange(db.Ads.OrderBy(x =&gt; x.Id).Where(x =&gt; x.Id &gt;= NextAd.Id).Take(count + 1));
  
          if(output.Count != count+1)
          {
              NextAd = db.Ads.First();
              output.AddRange(db.Ads.OrderBy(x =&gt; x.Id).Where(x =&gt; x.Id &gt;= NextAd.Id).Take(count - output.Count+1));
          }
  
          NextAd = output[count];
          output.RemoveAt(count);
  
          return output;
      }
  </code></pre>