Created
October 23, 2014 13:14
-
-
Save ctigeek/239d48d6ead6b2614e20 to your computer and use it in GitHub Desktop.
Return IEnumerable from a database query....
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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