Created
December 28, 2017 14:57
-
-
Save cryonautlex/b8f9e11bd89a19fb3f0b69cdafd82d55 to your computer and use it in GitHub Desktop.
FastQuery, a convenient way to run raw SQL queries in C#
This file contains hidden or 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
// Apache 2.0 license... This code might not work at all. | |
/// <summary> | |
/// Must reference parameters in the query positionally, starting with @p0. | |
/// </summary> | |
/// <typeparam name="T"></typeparam> | |
/// <param name="query">example is "select foo from bar where frob = @p0 and quux = @p1"</param> | |
/// <param name="selector"> | |
/// function that (usually) builds a new T from a database row-reader | |
/// </param> | |
/// <param name="parameterValues">values to substitute for the @p-parameters</param> | |
/// <returns>enumeration of the return values from selector</returns> | |
private IEnumerable<T> FastQuery<T>(string query, | |
Func<DbDataReader, T> selector, params object[] parameterValues) | |
{ | |
var result = new List<T>(); // @TODO use yield pattern instead | |
var conn = GetDbConnection(); | |
using (var command = conn.CreateCommand()) | |
{ | |
for (var i = 0; i < parameterValues.Length; i++) | |
{ | |
var parm = command.CreateParameter(); | |
parm.ParameterName = "@p" + i; | |
parm.Value = parameterValues[i]; | |
command.Parameters.Add(parm); | |
} | |
command.CommandText = query; | |
var reader = command.ExecuteReader(); | |
if (reader.HasRows) | |
{ | |
while (reader.Read()) | |
{ | |
var row = selector(reader); | |
result.Add(row); | |
// @TODO yield return instead | |
} | |
} | |
reader.Dispose(); | |
} | |
return result; // @TODO use yield pattern instead | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment