Skip to content

Instantly share code, notes, and snippets.

@AnthonyGiretti
Last active April 5, 2026 02:27
Show Gist options
  • Select an option

  • Save AnthonyGiretti/c9c04d4902d807549a7822cad9891624 to your computer and use it in GitHub Desktop.

Select an option

Save AnthonyGiretti/c9c04d4902d807549a7822cad9891624 to your computer and use it in GitHub Desktop.
Using EF Core to stream data from database handling paging
public class CountryService
{
private readonly IDbContextFactory<CountryDbContext> _contextFactory;
public CountryService(IDbContextFactory<CountryDbContext> contextFactory)
=> _contextFactory = contextFactory;
public async IAsyncEnumerable<Country> StreamCountries(
int startAfterId = 0,
[EnumeratorCancellation] CancellationToken ct = default)
{
var lastId = startAfterId;
while (!ct.IsCancellationRequested)
{
await using var context = await _contextFactory.CreateDbContextAsync(ct);
await foreach (var country in context.Countries
.Where(c => c.Id > lastId)
.OrderBy(c => c.Id)
.AsAsyncEnumerable()
.WithCancellation(ct))
{
lastId = country.Id;
yield return country;
}
await Task.Delay(2000, ct);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment