Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Return IEnumerable from a database query....
//Note: this was pretty much an acedemic exercise... I don't recommend using this pattern. IObservable would be much better suited.
class SomeRepository : IDisposable
private const string sql = "select * from sometable;";
private const string connString = @"Data Source=LOCALHOST\SQLEXPRESS;Initial Catalog=sandbox;Integrated Security=SSPI;";
public void Dispose()
if (reader != null) reader.Dispose();
if (connection != null) connection.Dispose();
connection = null;
private SqlConnection connection;
private SqlDataReader reader;
private bool rowExists = true;
public async Task<IEnumerable<Task>> RunQuery(Func<UserDataModel, Task> doThisForEachRow)
if (connection != null) throw new InvalidOperationException("A query is already in progress. Create a new object to run another query.");
connection = new SqlConnection(connString);
await connection.OpenAsync();
var command = new SqlCommand(sql, connection);
reader = await command.ExecuteReaderAsync();
if (!reader.Read())
return Enumerable.Empty<Task>();
return GetTasks(doThisForEachRow);
public IEnumerable<Task> GetTasks(Func<UserDataModel, Task> doThisForEachRow)
//this is the hackiest thing ever...
while (rowExists)
yield return GetData(doThisForEachRow);
private async Task GetData(Func<UserDataModel, Task> doThisForEachRow)
var model = new dataModel((string) reader["column1"], (string) reader["column2"]);
await doThisForEachRow(model);
rowExists = await reader.ReadAsync();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.