Skip to content

Instantly share code, notes, and snippets.

@KyleGobel
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KyleGobel/1164614ce4ade261b2e4 to your computer and use it in GitHub Desktop.
Save KyleGobel/1164614ce4ade261b2e4 to your computer and use it in GitHub Desktop.
This will take an embedded .sql resource file and return it's string contents. Auto mapping dtos to sql queries that can be easily run
public static class SqlQueryExtensions
{
public static string GetSqlQuery<T>(this T requestDto, Action<string> queryFilter = null, string queryNamespace = null, string filename = null) where T : class
{
const string delimiter = "--start";
var sqlStatement = string.Empty;
//expects the namespace of this file to be the same namespace as the sql query file
var namespacePart = queryNamespace ?? typeof(SqlQueryExtensions).Namespace;
//name is the same as the requestDto, but with a .sql extension
var resourceName = filename ?? (namespacePart + "." + typeof(T).Name + ".sql");
using (var stm = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
{
if (stm != null)
{
sqlStatement = new StreamReader(stm).ReadToEnd();
}
}
var startIndex = sqlStatement.IndexOf(delimiter, StringComparison.CurrentCultureIgnoreCase);
if (startIndex > 0)
{
return sqlStatement.Substring(startIndex + delimiter.Length);
}
if (queryFilter != null)
{
queryFilter(sqlStatement);
}
return sqlStatement;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment